SQLSyntaxErrorException异常产生原因及解决方案
作者:mmseoamin日期:2024-01-19

01 异常发生场景

  • 当我使用PreparedStatement 类进行数据库连接时,弹出错误

    Cause: 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 '? , studentNo=? , age=? ,  classId=? , phone=? , remark=? , sex=?' at line 1
    ​
    //以下是代码部分
    try {
    //            1.注册驱动
                Class.forName("com.mysql.cj.jdbc.Driver");
    //            2.获取连接对象,连接数据库
                connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/text012?userSSL=false&serverTimezone=Asia/Shanghai", "root", "1234");
    //            4.执行sql语句,返回对象
                String sql="insert into student (name, studentNo , age ,  classId , phone , remark , sex) values (?,?,?,?,?,?,?);";
                stmt=connection.prepareStatement(sql);
                stmt.setString(1,name);
                stmt.setString(2,studentNo);
                stmt.setInt(3,age);
                stmt.setInt(4,classId);
                stmt.setInt(5,phone);
                stmt.setString(6,remark);
                stmt.setString(7,sex);
    ​
                System.out.println(sql);
    //            3.获得查询执行者
                int num=0;
                num=stmt.executeUpdate(sql);
                System.out.println(num);
    //            5.解析对象,获得数据库的数据
                if (num!=0){
                    flag=true;
                }
    ​
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if (connection!=null){
                    connection.close();
                }
                if (rs!=null){
                    rs.close();
                }
                if (stmt!=null){
                    stmt.close();
                }    

    02 异常的产生原因