37 lines
1.3 KiB
Java
37 lines
1.3 KiB
Java
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();
|
|
}
|
|
}
|
|
} |