加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

jdbc批量数据插入的代码

发布时间:2020-05-24 16:01:57 所属栏目:Java 来源:互联网
导读:jdbc批量数据插入的代码

下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。

脚本之家小编现在分享给大家,也给大家做个参考。

1899942,一    
1899944,二  
1899946,三 
1899948,四  
1899950,五    
1899952,六    
1899954,和  
1899956,在 
1899958,的  
1899960,对 
1899962,需 
1899964,大规模  
1899966,压力 
1899968,大城市 
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。 
有几万条这样的数据需要插入数据库 

public class Main { 
public static void main(String[] args) throws Exception{ 
String sql = "insert into mobile_place(number,place) values(?,?)"; 
int count = 0;//计数器 
Connection conn = JDBCUtil.getConnection(); 
PreparedStatement pstmt = conn.prepareStatement(sql); 
try { 
InputStreamReader is = new InputStreamReader(new FileInputStream(new File("D:/CC.txt")),"utf-8"); 
BufferedReader br = new BufferedReader(is); 
while(br.readLine() != null){ 
conn.setAutoCommit(false);//设置数据手动提交,自己管理事务 
count++;//没读取一行数据,计数器+1 
String str = br.readLine().toString().trim();//读取一行数据 
String s1 = str.substring(0,str.indexOf(","));//取逗号以前的一段 
String s2 = str.substring(str.indexOf(",")+1,str.length());//取逗号之后的一段 
pstmt.setString(1,s1); 
pstmt.setString(2,s2); 
pstmt.addBatch();//用PreparedStatement的批量处理 

if(count%500==0){//当增加了500个批处理的时候再提交 
pstmt.executeBatch();//执行批处理 
conn.commit();//提交 
conn.close();//关闭数据库 
conn = JDBCUtil.getConnection();//重新获取一次连接 
conn.setAutoCommit(false); 
pstmt = conn.prepareStatement(sql); 
} 
System.out.println("已插入"+count+"条数据"); 
} 
if(count%500!=0){//while循环外的判断,为了防止上面判断后剩下最后少于500条的数据没有被插入到数据库 
pstmt.executeBatch(); 
conn.commit(); 
} 
pstmt.close(); 
conn.close(); 
} catch (Exception e) { 
e.printStackTrace(); 
} 
} 
} 
500可以自己增大,执行效率很高。比单挑执行再插入快多了 

getConnection()为获取数据库连接 
public static Connection getConnection(){ 
try { 
Class.forName("com.mysql.jdbc.Driver"); 
} catch (ClassNotFoundException e) { 
e.printStackTrace(); 
} 
try { 
conn = DriverManager.getConnection(url,userName,password); 
} catch (SQLException e) { 
e.printStackTrace(); 
} 
return conn; 
}

以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读