Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add multiple rows in sql using java

Tags:

java

mysql

jdbc

I know the simple method of adding one row into sql database using netbeans.

Here is that method:

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

Now, I want to add multiple rows in sql database. For example, in the code given below:

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

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

I want to add each line in sql till s.readLine() becomes null.

Kindly help me.

like image 636
zeeshan nisar Avatar asked Oct 30 '22 06:10

zeeshan nisar


1 Answers

You are doing it incorrectly! With your current code you'll end up missing alternate lines as you are calling readLine() twice but only outputting it the first time.

Also, if you want to insert multiple rows in your DB then you should be looking at a Batch.

Here is the JAVA Doc of addBatch():

Adds the given SQL command to the current list of commands for this Statement object. The commands in this list can be executed as a batch by calling the method executeBatch.

You should be doing something like this:

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

Here is how you can execute the Batch:

int[] result = stmt.executeBatch();
like image 198
user2004685 Avatar answered Nov 11 '22 08:11

user2004685