您的位置:首页 > 编程语言 > Java开发

Java 批量插入数据到数据库(MySQL)中

2016-07-14 17:42 543 查看
实现Java批量插入数据库数据:

package Proxy;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class TextReader{
public static void main(String args[]) {
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://" +
"localhost:3306/DP", "admin", "123456");
String sql = "Insert into ACT_cdKeytempsss (cdKey, ActivityId) VALUES (?,3577)";

String sqlupdate = "update ACT_cdKey set status=1 where CdKey = ?";

PreparedStatement ps = con.prepareStatement(sql);

PreparedStatement ps1 = con.prepareStatement(sqlupdate);

con.setAutoCommit(false); // 关闭事务自动提交

String pathname = "C:/Users/Administrator/Desktop/result8.txt";
File fileName = new File(pathname);

InputStreamReader reader = new InputStreamReader(new FileInputStream(fileName));
BufferedReader br = new BufferedReader(reader);
String line = "";
line = br.readLine();

while (line != null) {
ps.setString(1, line);
ps1.setString(1, line);
line = br.readLine();
ps.addBatch();
ps1.addBatch();
}

ps.executeBatch();
ps1.executeBatch();
con.commit();
ps.close();
ps1.close();
con.close();
br.close();
}
catch (Exception e) {
e.printStackTrace();// TODO: handle exception
}

}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: