中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

jdbc批量數(shù)據(jù)插入的代碼

2018-07-20    來源:open-open

容器云強(qiáng)勢上線!快速搭建集群,上萬Linux鏡像隨意使用
1899942 ,一    
1899944 ,二  
1899946 ,三 
1899948 ,四  
1899950 ,五    
1899952 ,六    
1899954 ,和  
1899956 ,在 
1899958 ,的  
1899960 ,對 
1899962 ,需 
1899964 ,大規(guī)模  
1899966 ,壓力 
1899968 ,大城市 
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。 
有幾萬條這樣的數(shù)據(jù)需要插入數(shù)據(jù)庫 

public class Main { 
public static void main(String[] args) throws Exception{ 
String sql = "insert into mobile_place(number,place) values(?,?)"; 
int count = 0;//計數(shù)器 
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);//設(shè)置數(shù)據(jù)手動提交,自己管理事務(wù) 
count++;//沒讀取一行數(shù)據(jù),計數(shù)器+1 
String str = br.readLine().toString().trim();//讀取一行數(shù)據(jù) 
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){//當(dāng)增加了500個批處理的時候再提交 
pstmt.executeBatch();//執(zhí)行批處理 
conn.commit();//提交 
conn.close();//關(guān)閉數(shù)據(jù)庫 
conn = JDBCUtil.getConnection();//重新獲取一次連接 
conn.setAutoCommit(false); 
pstmt = conn.prepareStatement(sql); 
} 
System.out.println("已插入"+count+"條數(shù)據(jù)"); 
} 
if(count%500!=0){//while循環(huán)外的判斷,為了防止上面判斷后剩下最后少于500條的數(shù)據(jù)沒有被插入到數(shù)據(jù)庫 
pstmt.executeBatch(); 
conn.commit(); 
} 
pstmt.close(); 
conn.close(); 
} catch (Exception e) { 
e.printStackTrace(); 
} 
} 
} 
500可以自己增大,執(zhí)行效率很高。比單挑執(zhí)行再插入快多了 

getConnection()為獲取數(shù)據(jù)庫連接 
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; 
}

標(biāo)簽: Mysql 數(shù)據(jù)庫

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請與原作者聯(lián)系。

上一篇:Java使用Spring發(fā)郵件

下一篇:Java獲取某年某周的最后一天