01 異常發(fā)生場景
-
當(dāng)我使用PreparedStatement 類進(jìn)行數(shù)據(jù)庫連接時,彈出錯誤
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.注冊驅(qū)動 ? ? ? ? ? ?Class.forName("com.mysql.cj.jdbc.Driver"); // ? ? ? ? ? 2.獲取連接對象,連接數(shù)據(jù)庫 ? ? ? ? ? ?connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/text012?userSSL=false&serverTimezone=Asia/Shanghai", "root", "1234"); // ? ? ? ? ? 4.執(zhí)行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.獲得查詢執(zhí)行者 ? ? ? ? ? ?int num=0; ? ? ? ? ? ?num=stmt.executeUpdate(sql); ? ? ? ? ? ?System.out.println(num); // ? ? ? ? ? 5.解析對象,獲得數(shù)據(jù)庫的數(shù)據(jù) ? ? ? ? ? ?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 異常的產(chǎn)生原因
-
num=stmt.executeUpdate(sql);部分不需要再次傳入sql
-
executeUpdate:執(zhí)行數(shù)據(jù)庫的更新、插入和刪除操作 ,返回改變記錄的行數(shù),但是使用PreparedStatement 類對傳入數(shù)據(jù)進(jìn)行加密時,在執(zhí)行到這個語句的時候數(shù)據(jù)庫系統(tǒng)會對()中sql 的語句進(jìn)行預(yù)編譯的處理
03 解決方式
-
放棄使用PreparedStatement 類,或者更簡單的文章來源:http://www.zghlxwxcb.cn/news/detail-809863.html
-
num=stmt.executeUpdate();部分不傳入字符串文章來源地址http://www.zghlxwxcb.cn/news/detail-809863.html
到了這里,關(guān)于SQLSyntaxErrorException異常產(chǎn)生原因及解決方案的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!