有人请帮助我。我正在做正确的事但我得到一个错误。它是一个链接到MYSQL wamp服务器的JAVA应用程序。
错误: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在第1行的“Chege”附近使用正确的语法
我的代码:
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;
}
}
答案 0 :(得分:3)
您的查询字符串不正确。应该类似于以下内容:
rs=st.executeQuery("SELECT Emp_Id, Emp_Name, Department "
+ "FROM staff WHERE Emp_Name = '"+EmpName+"'");
但我建议使用PreparedStatement对象将SQL语句发送到数据库。
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();
这种方法更安全,更方便。
答案 1 :(得分:1)
您的查询中存在一些问题:
try {
st = con.createStatement();
//Add quotes 'YourString'
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);
}
或安全查询使用预备声明:
try {
PreparedStatement ps = connection.prepareStatement("SELECT Emp_Id, Emp_Name, Department FROM staff WHERE Emp_Name = ?");
ps.setString(1, EmpName);
rs = ps.executeUpdate();
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);
}