技术分享 ——JDBC
技术分享 ——JDBC
导入依赖
在使用 JDBC 前,首先要导入数据库依赖,每个数据库依赖不同。例如,MYSQL 的依赖如下:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
将该段代码放在 pom 文件的<dependencies>
下。
配置 MySQL
首先检查 MySQL 是否安装,安装后可在 IDEA 中链接数据库。新建 MySQL 的链接。
代码实现
增
import java.sql.*;
public class insert {
public static void main(String[] args) throws Exception {
String url="jdbc:mysql://localhost:3306/student";
String user="root";
String password="yourpassword";
Connection connection=DriverManager.getConnection(url,user,password);
PreparedStatement preparedStatement = connection.prepareStatement("insert into user(name,age) values(?,?)");
preparedStatement.setString(1,"小美");
preparedStatement.setInt(2,18);
int i = preparedStatement.executeUpdate();
if(i>0){
System.out.println("插入成功");
}else {
System.out.println("插入失败");
}
connection.close();
}
}
删
import java.sql.*;
public class delete {
public static void main(String[] args) {
String jdbcURL = "jdbc:mysql://localhost:3306/student";
String username = "root";
String password = "yourpassword";
try (Connection connection = DriverManager.getConnection(jdbcURL, username, password);
PreparedStatement preparedStatement = connection.prepareStatement("delete from user where name=? and id=?")) {
preparedStatement.setString(1, "xiaohong");
preparedStatement.setInt(2, 1);
int rowsAffected = preparedStatement.executeUpdate();
System.out.println("Rows affected: " + rowsAffected);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
改
import java.sql.*;
public class update {
public static void main(String[] args) {
String jdbcURL = "jdbc:mysql://localhost:3306/student";
String username = "root";
String password = "yourpassword";
try (Connection connection = DriverManager.getConnection(jdbcURL, username, password);
PreparedStatement preparedStatement = connection.prepareStatement("update user set name = ? where id = ?")) {
preparedStatement.setString(1, "xiaohong");
preparedStatement.setInt(2, 1);
int rowsAffected = preparedStatement.executeUpdate();
System.out.println("Rows affected: " + rowsAffected);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
查
import java.sql.*;
public class select {
public static void main(String[] args) {
String jdbcURL = "jdbc:mysql://3306/student";
String username = "root";
String password = "yourpassword";
try (Connection connection = DriverManager.getConnection(jdbcURL, username, password);
PreparedStatement preparedStatement = connection.prepareStatement("SELECT id,name FROM user")) {
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String name = resultSet.getString("name");
int id = resultSet.getInt("id");
System.out.println("Column1: " + id + ", Column2: " + name);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
技术分享 ——JDBC
https://fengliangit.cn:9999/archives/434599c2-094e-42dd-afbb-523b621c8461