如何使用 JDBC 在 MySQL 中轉義反斜槓?


若要轉義反斜槓,請使用 PreparedStatement 來插入記錄。首先,我們建立一個表 -

mysql> create table DemoTable1904
   (
   ClientId int,
   ClientName varchar(20),
   ClientAge int
   );
Query OK, 0 rows affected (0.00 sec)

Java 程式碼如下 -

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class EscapeBackslashesDemo {
   public static void main(String[] args) {
      Connection con = null;
      PreparedStatement ps = null;
      try {
         con = DriverManager.getConnection("jdbc:mysql://:3306/web?" + "useSSL=false", "root", "123456");
         String query = "insert into DemoTable1904(ClientId,ClientName,ClientAge) values(?,?,?) ";
         ps = con.prepareStatement(query);
         ps.setInt(1, 1001);
         ps.setString(2, "David Miller");
         ps.setInt(3, 35);
         ps.executeUpdate();
         System.out.println("One row is inserted.....");
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

這將產生以下輸出 -

我們來查看錶記錄 -

mysql> select * from DemoTable1904;

這將產生以下輸出 -

+----------+--------------+-----------+
| ClientId | ClientName   | ClientAge |
+----------+--------------+-----------+
|     1001 | David Miller |        35 |
+----------+--------------+-----------+
1 row in set (0.00 sec)

更新日期: 2019-12-30

瀏覽量 338

開啟您的事業

完成課程獲得認證

開始
廣告
© . All rights reserved.