JDBC delete statement with multiple columns - java

It says I ended this statement wrong when if I input it into sql plus with just the addition of ; it works perfectly. What am I doing wrong?
Statement statement = connection.createStatement();
statement.executeUpdate("delete from aplbuk MODEL = '"+ textField_4.getText() + "'AND year = '" + textField_1.getText() + "' AND Litres = '" + textField_2.getText()
+ "' AND ENGINE_TYPE = '" + textField_3.getText() + "'");
statement.close();

Keyword where is missing after table name aplbuk in your query delete from aplbuk MODEL.
Update the query as:
statement.executeUpdate("delete from aplbuk where MODEL = '"+
textField_4.getText() + "'AND year = '" +
textField_1.getText() + "' AND Litres = '" +
textField_2.getText() + "' AND ENGINE_TYPE = '" +
textField_3.getText() + "'");
Also if year and Litres are numeric fields then don't enclose the value in single quotes.

Related

Database query and Java

I'm studying at a project about the creation of simple web application.
I'm creating a webapp about an Hotel and I have a problem about the reservation of a room.
I have 3 kind of rooms and I want when someone book a room, another one can't book the same room in the same period.
The problem is about this kind of control.
I have write this code:
UPDATE CODE AFTER AN ANSWER
Statement st = con.createStatement();
Statement stmt = con.createStatement();
out.println("connection successfull");
int total = 0;
ResultSet rs3 = stmt.executeQuery( "SELECT COUNT(*) as total FROM reservation WHERE idRoom = '" + idRoom +
"' AND ('" + arrivaldate + "' >= arrivaldate AND '" + arrivaldate + "' <= departuredate) OR ('" + departuredate + "' >= arrivaldate "
+ "AND '" + departuredate + "' <= departuredate)");
rs3.next(); // You'll ever have only one row
total = rs3.getInt("total");
/* String query = "SELECT COUNT(*) FROM reservation WHERE idRoom = '" + idRoom +
"' AND ('" + arrivaldate + "' >= arrivaldate AND '" + arrivaldate + "' <= departuredate) OR ('" + departuredate + "' >= arrivaldate "
+ "AND '" + departuredate + "' <= departuredate)" ;
*/
// ResultSet rs2 = stmt.executeQuery(check);
out.println("<h1> Stringa check eseguito </h1>");
if( total > 0) { // THIS DOESN't WORK OF COURSE
response.sendRedirect("home.jsp");
}
else {
st.executeUpdate("insert into reservation (login,email,typeroom,idRoom,arrivaldate,departuredate)values ('"+login+"','"+email+"','"+typeroom+"','"+idRoom+"','"+arrivaldate+"','"+departuredate+"')");
}
But it doesn't work properly because it lets me to book the same room in the same data.
How can I do in your opinion? Thank you for your attention.
First, you totally ignore your total:
while(rs3.next()){
rs3.getInt("total");
}
Should be:
rs3.next(); // You'll ever have only one row
total = rs3.getInt("total");
And second, never ever use concatenations in your queries:
ResultSet rs3 = stmt.executeQuery( "SELECT COUNT(*) as total FROM reservation WHERE idRoom = '" + idRoom +
"' AND ('" + arrivaldate + "' >= arrivaldate AND '" + arrivaldate + "' <= departuredate) OR ('" + departuredate + "' >= arrivaldate "
+ "AND '" + departuredate + "' <= departuredate)");
Always use PreparedStatements instead:
PreparedStatement ps = stmt.prepareStatement( "SELECT COUNT(*) as total FROM reservation WHERE idRoom = ? AND (? >= arrivaldate AND ? <= departuredate) OR (? >= arrivaldate AND ? <= departuredate)");
int c = 0;
ps.setInt(++c, idRoom);
ps.setDate(++c, arrivaldate);
ps.setDate(++c, departuredate);
ps.setDate(++c, arrivaldate);
ps.setDate(++c, departuredate);
ResultSet rs = ps.executeQuery();
// And your usual code here

Error in linking mysql and netbeans data

I am working with mysql and Netbeans java for my school project. Whenever I try to register the details to the sql, I get this error My SqlSyntaxErrorException:Unknown Column " [the data in the text field] in 'field list'"
Here's my code:
int age = Integer.parseInt(AgeTF.getText());
String name=NameTF.getText();
String id=IDTF.getText();
String dob=DobTF.getText();
String address=AddressTF.getText();
try {
Class.forName("java.sql.Driver");
String database = "jdbc:mysql://localhost:3306/final";
Connection conn = DriverManager.getConnection(database, "root", "sanchit");
Statement stmt = conn.createStatement();
String sql = "insert into aadhar values ( '" + id + "', " + name + ", '" + dob + "' , '" + age + "' , '" + address + "' );" ;
stmt.executeUpdate(sql);
}
catch( Exception e){
JOptionPane.showMessageDialog(null,"" + e);
}
JOptionPane.showMessageDialog(this,"You have been registered!");
Please help.
Thanks
You didn't protect name with simple quotes :
Write '" + name + "' instead of " + name + "
String sql = "insert into aadhar values ( '" + id + "', '" + name + "', '" + dob + "' , '" + age + "' , '" + address + "' );" ;

Having Syntax Error in code java

Why is there a syntax error in this code?
String strSqlUpdate = "UPDATE Customers SET Contact = " + contact_num + ","
+ "Email = '" + email_add + "',"
+ "Address = '" + mail_add + "',"
+ "SurveyStatus = " + radio_group + ","
+ "Subscription = " + receive_info +
"WHERE membership_ID = '" + member_ID';
I thought my code was right.
If it is the error in your code, check all the variables that you have used are declared and initialized with proper values.
If it is the syntax of the sql that is bothering you , here is what your sql would look like if all the variables are initialized to null.
UPDATE Customers SET (Contact)null,Emailnull,Address,null,SurveyStatus,null,SubscriptionnullWHERE MembershipID =null
Use spaces in your strSqlUpdate to correct the above sql.
EDIT
What you need is something like this.
String strSqlUpdate = "UPDATE Customers SET Contact = " + contact_num
+ ",Email = '" + email_add + "'"
+ ",Address = '" + mail_add + "'"
+ ",SurveyStatus = '" + radio_group + "'"
+ ",Subscription = '" + receive_info + "' "
+ "WHERE membership_ID = '" + member_ID + "'";
I get no syntax errors when I declare and Initialize all of the variables. You have to make sure they're all initialized, within the scope of the strSqlUpdate
String contact_num = "";
String email_add = "";
String mail_add = "";
String radio_group = "";
String receive_info = "";
String member_ID = "";
String strSqlUpdate = " UPDATE Customers SET (Contact)" + contact_num + "," + "Email"
+ email_add + "," + "Address" + "," + mail_add + "," + "SurveyStatus" + "," + radio_group
+ "," + "Subscription" + receive_info + "WHERE MembershipID =" + member_ID;
Also considering you're talking about SQL syntax, adding on to what others have said, I'd advise you should use a PreparedStatement to avoid SQL injection.
PreparedStatement pst = conn.prepareStatement(
"UPDATE Customers SET (Contact) ?, ?, ?, ?, ?, ?, ? WHERE ? = ?");
pst.setString(1, contact_num);
pst.setString(2, email_add);
... and so on
An error in your current SQL syntax is this
"Subscription" + receive_info + "WHERE MembershipID
Translated as
"...Subscrptionreceive_infoWHERE MembershipID..."
You need to add spaces wherever you don't have commas

nested if for sql results

Guys I am struggling to create search queries for a database I am developing but the user choices are so many! I don't know how to filter them out! Do I have to create a different query for EVERY SINGLE choice the user checks? If he wants to search for name only, that's an other query. Name and surname is an other. Age and country is another! I don't know how to do that without writing hundreds of lines of code! I have tried this example but it only works if the user fills every textfield.
private void searchB_actionPerformed(ActionEvent e) {
query = "SELECT agent_id, name, surname, clearance, user_id, alias, missions, age, country, current_mission FROM agents WHERE " ;
if (!agentidTF.getText().isEmpty()) {
query = query + "agent_id = '" + agentidTF.getText() + "' ";
//System.out.println(query);
if (!nameTF.getText().isEmpty()) {
query = query + " AND name = '" + nameTF.getText().toUpperCase() + "' ";
//System.out.println(query);
if (!surnameTF.getText().isEmpty()) {
query = query + " AND surname = '" + surnameTF.getText().toUpperCase() + "' ";
//System.out.println(query);
if (clearancebox.getSelectedItem() != "SELECT CLEARANCE") {
query =
query + " AND clearance = '" + clearancebox.getSelectedItem().toString().toUpperCase() +
"' ";
//System.out.println(query);
if (!useridTF.getText().isEmpty()) {
query = query + " AND user_id = '" + useridTF.getText() + "' ";
//System.out.println(query);
if (!ageTF.getText().isEmpty()) {
query = query + " AND age = '" + ageTF.getText() + "' ";
//System.out.println(query);
if (!aliasTF.getText().isEmpty()) {
query = query + " AND alias = '" + aliasTF.getText().toUpperCase() + "' ";
//System.out.println(query);
if (!currmissTF.getText().isEmpty()) {
query =
query + " AND current_mission = '" + currmissTF.getText().toUpperCase() +
"' ";
//System.out.println(query);
if (countrybox.getSelectedItem() != "SELECT COUNTRY") {
query =
query + " AND country = '" + countrybox.getSelectedItem().toString().toUpperCase() +
"' ";
//System.out.println(query);
} //end of countrybox
} //end of currmissTF
} //end of aliasTF
} //end of ageTF
} //end of useridTF
} //end of clearancebox
} //end of surnameTF
} //end of nameTF
} //end of agentidTF
query = query + " ORDER BY agent_id";
System.out.println("ACTUALL QUERY IS: " + query);
}

DB2 Error SQLCODE=-103, SQLSTATE=42604

I am trying to update a table, but it isn't working and giving this sql error.
//Updating Buy Table
Integer stkbid = Integer.parseInt(request.getParameter("stockBid"));
System.out.println("stock buy id : " + stkbid);
//get buy details
PreparedStatement stmtbuy = conn.prepareStatement(
"SELECT \"StockSymbol\", \"Unit\", \"Price\", \"ClearingFee\", \"StampDuty\", \"BrokerFee\"" +
"FROM SPM.\"StockBuy\" WHERE \"StockBuyId\" = '"+ stkbid + "'");
System.out.println("Got stock buy details");
ResultSet rs=stmtbuy.executeQuery();
rs.next();
//String stkcode = rs.getString("StockSymbol");
Integer stkunit = Integer.parseInt(rs.getString("Unit"));
stkunit -= stock.getStockUnit();
Double stkprice = Double.parseDouble(rs.getString("Price"));
Double stkclear = Double.parseDouble(rs.getString("ClearingFee"));
Double stksd = Double.parseDouble(rs.getString("StampDuty"));
Double stkbfee = Double.parseDouble(rs.getString("BrokerFee"));
Double stkval = stkunit * stkprice;
Double stknv = stkval + stkval * (stkclear + stksd + stkbfee);
System.out.println(stknv);
PreparedStatement stmtbuy1 = conn.prepareStatement(
"UPDATE SPM.\"StockBuy\" SET \"Unit\" = " + stkunit + ", \"Value\" = " + stkval + ", \"NetValue\" = " + stknv +
"WHERE \"StockBuyId\" = "+ stkbid);
You are missing a space in before the WHERE clause, which messed up your stknv.
" WHERE \"StockBuyId\" = "+ stkbid);
I think it's an obligation of any poster to remind you that you should use parametrized query. So I shall do the same.
"Please use parametrized query!"
The query that is works has a quote at the end:
" WHERE \"StockBuyId\" = '"+ stkbid + "'");
The one that fails does not
"WHERE \"StockBuyId\" = "+ stkbid);
That might have something to do with it.

Categories