向数据库写入数据

This commit is contained in:
seahi 2024-12-17 09:52:40 +08:00
parent a21a66a542
commit 6719f1e7b2

View File

@ -0,0 +1,37 @@
package chapter10;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
public class Example02 {
public static void main(String[] args) {
try {
// 1. 加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 2. 准备连接参数
String url = "jdbc:mysql://localhost:3306/school?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC";
String username = "root";
String password = "root";
// 使用try-with-resources自动关闭资源
try (
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement()
) {
// 准备INSERT语句
String sql = "INSERT INTO student (name, age, gender, class, score) " +
"VALUES ('小张', 19, 'M', '计算机1班', 88.5)";
// 执行INSERT语句
int rows = statement.executeUpdate(sql);
// 输出受影响的行数
System.out.println("成功插入 " + rows + " 条数据");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}