日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

SQLSyntaxErrorException異常產生原因及解決方案

作者:宣布無人罪 更新時間: 2023-12-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 異常的產生原因

  • num=stmt.executeUpdate(sql);部分不需要再次傳入sql

  • executeUpdate:執行數據庫的更新、插入和刪除操作 ,返回改變記錄的行數,但是使用PreparedStatement 類對傳入數據進行加密時,在執行到這個語句的時候數據庫系統會對()中sql 的語句進行預編譯的處理

03 解決方式

  • 放棄使用PreparedStatement 類,或者更簡單的

  • num=stmt.executeUpdate();部分不傳入字符串

原文鏈接:https://blog.csdn.net/2302_77182979/article/details/132650047

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新