Wannabe JavaGeek Wannabe JavaGeek - 6 months ago 22
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.

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


public class MyQuery {

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


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.