今天在写JDBC中的一个小项目时,遇到了这样这个问题:
SQLSyntaxErrorException(SQL语法错误异常)
java.sql.SQLSyntaxErrorException: 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 'and loginPwd = '456'' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1198)
at JDBCTest06.login(JDBCTest06.java:56)
at JDBCTest06.main(JDBCTest06.java:11)
反反复复找了半个小时,最后才发现是SQL语句多了一个“=”符合,导致语法出错
修改前(代码片段):
try {
//1、注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2、获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","lyc020203");
//3、获取数据库操作对象
stmt = conn.createStatement();
//4、执行sql
String sql = "select * from t_user where loginName = '"+loginName+"'=and loginPwd = '"+loginPwd+"'";
rs = stmt.executeQuery(sql);
//5、处理结果集
if(rs.next()){
loginSuccess = true;
}
修改后:
String sql = "select * from t_user where loginName = '"+loginName+"'and loginPwd = '"+loginPwd+"'";