Reputation: 43
I am writing a simple JDBC program using MySQL but Whats' WRONG with one line. I don't see any thing wrong but below mention line showing error while running the program
Code -
ResultSet recs = psmt.executeQuery("select * from item_master where catid = "+id1 +"and des = '" +sString+"';");
Error -
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'des = 'LG computer' ' at line 1
I also test this query in MySQL and got the output -
select * from item_master where catid = 2 and des = 'LG computer';
But Java not allowing me execute this line. I also tried with LIKE
select * from item_master where catid = 2 and des LIKE 'LG computer';
Upvotes: 1
Views: 178
Reputation: 201419
You're missing a space after the int
, and you don't need a semicolon in the query. Something like,
"select * from item_master where catid = "+id1 +" and des = '" +sString+"'"
or
String.format("select * from item_master where catid = %d and des = '%s'",
id1, sString);
or, my preference, use a PreparedStatement
String query = "select * from item_master where catid = ? and des = ?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setInt(1, id1);
ps.setString(2, sString);
try (ResultSet rs = ps.executeQuery()) {
// ...
}
} catch (SQLException e) {
e.printStackTrace();
}
Upvotes: 2