2016-03-30 35 views
3

我知道使用NetBeans將一行添加到sql數據庫的簡單方法。使用java在sql中添加多行

這裏是一個方法:

Class.forName("com.mysql.jdbc.Driver"); 
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/zeeshan", 
               "root","sHaNi97426"); 
Statement stmt = (Statement)conn.createStatement(); 
String insert = "INSERT INTO clients VALUES('"+hostname+"');"; 
stmt.executeUpdate(insert); 

現在,我想在sql數據庫添加多行。例如,代碼如下:

Process p = Runtime.getRuntime().exec("tasklist.exe"); 
BufferedReader s = new BufferedReader(new InputStreamReader(p.getInputStream())); 

while ((s.readLine()) != null) { 
    System.out.print(s.readLine()); 
} 

我想添加的每一行的SQL直到s.readLine()變得null

請幫助我。

回答

2

你做得不對!使用您當前的代碼,您最終會丟失備用行,因爲您要撥打readLine()兩次,但只能在第一次輸出。

另外,如果你想在數據庫中插入多行,那麼你應該看看Batch

這裏是addBatch()的JAVA文件:

將給定的SQL命令來此Statement對象的命令的當前列表。這個列表中的命令可以通過調用executeBatch方法以批處理方式執行。

你應該做這樣的事情:

String input = null; 
while ((input = s.readLine()) != null) { 
    stmt.addBatch(input); 
} 

這裏是你如何執行批處理:

int[] result = stmt.executeBatch();