通过jdk向MySql数据库批量插入数据
程序员文章站
2022-04-04 23:24:13
...
一、在ide中新建一个maven项目(project)
注意:创建项目前,确保mawen的仓库地址已经配置正确(与maven安装时候的地址一致),否则打包的时候会出错
二、新建包com.test、新建类TestSql
三、在TestSql类中编辑代码
package com.test;
import java.sql.*;
public class TestSql {
public static void main(String[] args) throws SQLException {
Connection conn = null;
System.out.println(“数据库连接开始…”);
try {
Class.forName(“com.mysql.cj.jdbc.Driver”);
String url = “jdbc:mysql://localhost:3306/testsql?serverTimezone=GMT%2B8”; //testsql是已经在mysql中创建的仓库
String user = “"; //mysql账号
String password = "********”; //mysql密码
conn = DriverManager.getConnection(url, user, password);
if (!conn.isClosed()) {
System.out.println("成功连接数据库!");
} else {
System.out.println("连接数据库失败!");
}
Statement statement = conn.createStatement();
conn.setAutoCommit(false); //关闭自动提交
String sql;
for (int i = 0; i < 10; i++) {
for (int k = 0; k < 1000; k++) {
int j = i*1000+k;
sql = "insert into new_table(line01,line02) values ('" + j + "','" + (j + 1) + "')"; //插入的SQL语句。new_table是已经在数据库testsql中创建的表,line01、line02是字段名
statement.executeUpdate(sql);
}
conn.commit(); //每1000次向数据库此提交一次,可提高程序效率
}
sql = "select * from new_table";
ResultSet rs = statement.executeQuery(sql);
System.out.println("执行结果如下:");
System.out.println("line01" + "\t" + "line02");
System.out.println("--------------");
String one = null;
String two = null;
while (rs.next()) {
one = rs.getString("line01");
two = rs.getString("line02");
System.out.println(one + "\t" + "\t" + two);
}
statement.close();
rs.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
三、在pom.xml配置文件中,增加依赖,引入数据库连接所需要的包
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
</dependencies>
上一篇: Linux安装JDK
下一篇: 连接数据库