Java_JDBC一般写法

时间:2021-10-19 00:21:57

JDBC是Java DataBase Connectivity,Java程序访问数据库的标准接口。

Java_JDBC一般写法

如果是maven工程先加入依赖的jar包:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>

Statement

String url = "jdbc:mysql://localhost:3306/test_db";
String userName = "root";
String password = "123";
try(Connection conn = DriverManager.getConnection(url, userName,password)) {
try(Statment sm = conn.createStatement()) {
String name = "小明";
try (ResultSet sm = ps.excuteQuery("SELECT * FROM test_table WHERE name='"+ +"'")) {
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
}
}

PreparedStatement

1.查询

String url = "jdbc:mysql://localhost:3306/test_db";
String userName = "root";
String password = "123";
try(Connection conn = DriverManager.getConnection(url, userName,password)) {
try(PreparedStatment ps = conn.preparedStatement("SELECT * FROM test_table WHERE name=?")) {
ps.setObject(1, "rick");
try (ResultSet rs = ps.excuteQuery()) {
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
}
}

2.新增、更新、删除

String url = "jdbc:mysql://localhost:3306/test_db";
String userName = "root";
String password = "123";
try(Connection conn = DriverManager.getConnection(url, userName,password)) {
try(PreparedStatment ps = conn.preparedStatement("UPDATE test_table SET age = ? WHERE name=?")) {
ps.setObject(2, "rick");
ps.setInt(1, 18);
int n = ps.excuteQuery(); //成功执行的数据条数
}
}