MySQL 如何使用JDBC转义反斜杠
要转义反斜杠,插入记录时使用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://localhost: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("插入了一行数据.....");
} catch (Exception e) {
e.printStackTrace();
}
}
}
这将产生以下输出 –

让我们检查表记录 –
mysql> select * from DemoTable1904;
这将产生以下输出 –
+----------+--------------+-----------+
| ClientId | ClientName | ClientAge |
+----------+--------------+-----------+
| 1001 | David Miller | 35 |
+----------+--------------+-----------+
1 row in set (0.00 sec)
阅读更多:MySQL 教程
极客教程