第一步,连接数据库
try {
Class.forName("com.mysql.jdbc.Driver");
// 建立与数据库的Connection连接
// 这里需要提供:
// 数据库所处于的ip:127.0.0.1 (本机)
// 数据库的端口号: 3306 (mysql专用端口号)
// 数据库名称 how2java
// 编码方式 UTF-8
// 账号 root
// 密码 admin
Connection c = DriverManager
.getConnection(
"jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8",
"root", "");
System.out.println("连接成功,获取连接对象: " + c);
} catch (ClassNotFoundException e) {
// 捕获类找不到异常
e.printStackTrace();
} catch (SQLException e) {
// 捕获SQL异常
e.printStackTrace();
}
第二步,获取statement对象
try {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager
.getConnection(
"jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8",
"root", "");
// 注意:使用的是 java.sql.Statement
// 不要不小心使用到: com.mysql.jdbc.Statement;
Statement s = c.createStatement();
System.out.println("获取 Statement对象: " + s);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
第三步,插入数据
Connection c = null;
Statement s = null;
try {
Class.forName("com.mysql.jdbc.Driver");//加载MySQL JDBC驱动程序并使其可用于Java应用程序中的数据库连接
c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root",
"");
s = c.createStatement();
// 插入一条数据到表hero中,值为:null,'提莫1',313.0,50
String sq1 = "insert into hero values(null," + "'测试0'" + "," + 313.0f + "," + 50 + ")";
s.execute(sq1);
String sq2 = "insert into hero values(null," + "'测试00'" + "," + 313.0f + "," + 50 + ")";
s.execute(sq2);
String sql = "insert into hero (name, hp, damage) values (?, ?, ?)";
PreparedStatement ps = c.prepareStatement(sql);//PreparedStatement预编译的SQL语句
for(int i = 1; i <= 100; i ++) {
ps.setString(1, "hero" + i);// 为第一个占位符设置字符串类型的值,即name列的值为"hero" + i
ps.setInt(2, 100);
ps.setInt(3, 5);
ps.execute();
}
System.out.println("执行插入语句成功");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//数据库的连接时有限资源,相关操作结束后,养成关闭数据库的好习惯
// 先关闭Statement
if (s != null)
try {
s.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Statement关闭成功");
// 后关闭Connection
if (c != null)
try {
c.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Connection关闭成功");
}
PreparedStatement对象中的SQL语句包含了3个占位符,分别对应插入语句中的三个问号。通过setString()和setInt()方法分别为这些占位符设置具体的值。第一个占位符的索引为1,第二个占位符的索引为2,第三个占位符的索引为3。在循环中,每次执行插入操作时,通过修改字符串和整数值的拼接来设置name、hp和damage列的值,从而实现100条记录的插入。