Wannabe JavaGeek Wannabe JavaGeek - 4 months ago 13
SQL Question

MySQLSyntaxErrorException in JAVA

Somebody please help me.I am doing things right but i am getting an error.It is a JAVA application linked to MYSQL wamp server.

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 'Chege' at line 1

MY CODE:

public class MyQuery {

public Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://"
+ "localhost:3306/employee_certificate", "root", "");
} catch (SQLException ex) {
Logger.getLogger(Query.class.getName())
.log(Level.SEVERE, null, ex);
}
return con;
}

public ArrayList<Item> getData(String EmpName) {
ArrayList<Item> list = new ArrayList<Item>();
Connection con = getConnection();
Statement st;
ResultSet rs;
try {
st = con.createStatement();
rs = st.executeQuery("SELECT Emp_Id, Emp_Name, Department "
+ "FROM staff WHERE Emp_Name = " + EmpName + " ");
Item I;
while (rs.next()) {
I = new Item(
rs.getString("Emp_Id"),
rs.getString("Emp_Name"),
rs.getString("Department"));
list.add(I);
}
} catch (SQLException ex) {
Logger.getLogger(Query.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
}

Answer

Your query string is not correct. Should be something like following:

rs=st.executeQuery("SELECT Emp_Id, Emp_Name, Department "
          + "FROM staff WHERE Emp_Name = '"+EmpName+"'");

But I'd recommend to use a PreparedStatement object for sending SQL statements to the database.

String query = "SELECT Emp_Id, Emp_Name, Department FROM staff WHERE Emp_Name = ?";
PreparedStatement preStatement = conn.prepareStatement(query);
preStatement.setString(1, EmpName);
ResultSet result = preStatement.executeQuery();

This approach is safer and more convenient.

Comments