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

jdbc批量数据插入的代码

发布时间:2020-12-15 00:14:46 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 1899942,一 1899944,二 1899946,三 1899948,四 1899950,五 1899952,六 1899954,和 1899956,在 1899958,的 1899960,对 1899962,需 1899964,大规模 1899

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

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; 
}

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

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

    推荐文章
      热点阅读