JBDC batch insert not looping over correctly - java

I'm currently trying to insert values from a String Array into the three columns within my database
e.g. list 1 into column 1 and so forth. But having issues using the batch insert within the loop. Here is my current code and from what I can gather the only way to do this is by looping over each String Array inserting values unless there is a better way.
PreparedStatement stmt = conn.prepareStatement("INSERT INTO Scores (Home, Score, Away) VALUES (?, ?, ?)");
String[] List1str = new String[List1.size()];
List1str = List1.toArray(List1str);
String[] List2str = new String[List2.size()];
List2str = List2.toArray(List2str);
String[] List3str = new String[List3.size()];
List3str = List3.toArray(List3str);
for (String s1 : List1str) {
stmt.setString(1, s1);
for (String s2 : List2str) {
stmt.setString(2, s2);
for (String s3 : List3str) {
stmt.setString(3, s3);
stmt.addBatch();
}
}
}
stmt.executeBatch();

You should bind all strings before do addBatch().
Currently your addBatch() in last nested loop.
If we take in assumption that all lists has same size, your code should be following:
for (int i=0; i<List1.size(); i++) {
stmt.setString(1, List1[i]);
stmt.setString(2, List2[i]);
stmt.setString(3, List3[i]);
stmt.addBatch();
}
stmt.executeBatch();

Related

How to insert List<String[]> data into database using JDBC?

The current format of my List<String[]> is:
60 52 0 0 1512230400
76 52 1 1 1514044800
42 52 4 1 1516464000
Whereby each separated value by space is a row in my database table, for example: 60 52 0 0 1512230400. I want to insert the 5 separate values per loop. I want to insert all these lines into my database but am not sure on exactly how. This is also a working connection to my database as of now.
This is my rough idea:
String query = "INSERT INTO games (team1_id, team2_id, score1, score2, created_at) VALUES (? ,?, ?, ?, ? )";
Connection con = DBConnector.connect();
PreparedStatement stmt = con.prepareStatement(query);//prepare the SQL Query
for (String[] s : fixtures) {
}
Any help is amazing.
Many thanks
In your for-loop, you can do something like this:
stmt.setString(1, s[0]); //team1_id if it's of string type in db
stmt.setInt(2, Integer.parseInt(s[1])); //team2_id if it's of type integer in db
stmt.setInt(3, Integer.parseInt(s[2])); //score1
stmt.setInt(4, Integer.parseInt(s[3])); //score2
stmt.setLong(5, Long.parseLong(s[4])); //created_at
stmt.executeUpdate();
The above code shows you how to deal with String, Long and Integer, you can use other types similarly.
List<String[]> fixtures = new ArrayList<>();
fixtures.add(new String [] {"60","52","0","0","1512230400"});
fixtures.add(new String [] {"76","52","1","1","1514044800"});
fixtures.add(new String [] {"42","52","4","1","1516464000"});
String query =
"INSERT INTO games (team1_id, team2_id, score1, score2, created_at)\n"
+ " VALUES (? ,?, ?, ?, ? )";
try(
Connection con = DBConnector.connect();
PreparedStatement stmt = con.prepareStatement(query);
) {
for (String[] s : fixtures) {
stmt.setString(1,s[0]);
stmt.setString(2,s[1]);
stmt.setString(3,s[2]);
stmt.setString(4,s[3]);
stmt.setString(5,s[4]);
stmt.execute();
}
con.commit();
}
With this approach, we pass the bind variables as strings. If needed, based on the actual type of the columns being inserted to, conversion from string (VARCHAR) to numeric (NUMBER) will happen by the database.
You got basically all of it right, but didn't take the next step of actually setting the bind-variables ...
This can work if the input List is already created:
List<String[]> fixtures = ...; // assuming this data is already created
String query = "INSERT INTO games (team1_id, team2_id, score1, score2, created_at) VALUES (? ,?, ?, ?, ? )";
try (Connection con = DBConnector.connect();
PreparedStatement stmt = con.prepareStatement(query)) {
for (String [] row : fixtures) {
// This gets executed for each row insert
for (int i = 0; i < row.length; i++) {
stmt.setInt(i+1, Integer.parseInt(row[i]);
}
stmt.executeUpdate();
}
}
catch(SQLException ex) {
ex.printStackTrace();
// code that handles exception...
}

Microsoft SQL Server Prepared statement within a for loop not working

I need help with the following. I am trying in 2 ways. Both did not work. No rows updated. The same sql works without the loop (for a single string). But I want to execute the same sql for multiple strings.
Method1:
PreparedStatement pstmt = null;
String query = "UPDATE PeopleTable SET firstname = CAST(REPLACE(CAST(firstname as nvarchar(max)), ? ,'ReplacedFirstName') as ntext)";
pstmt = conn.prepareStatement(query);
for(String s: myList) {
pstmt.setString(1, s);
pstmt.addBatch();
}
pstmt.executeUpdate();
Method:2:
PreparedStatement pstmt = null;
String query = "UPDATE PeopleTable SET firstname = CAST(REPLACE(CAST(firstname as nvarchar(max)), ? ,'ReplacedFirstName') as ntext)";
pstmt = conn.prepareStatement(query);
for(String s: myList) {
pstmt.setString(1, s);
pstmt.executeUpdate();
stmt.clearParameters();
}
Both are not working. Please help.

every row from the database being one JList item?

I currently have a database that is working well. It displays the text from each column of the database into 5 labels on the app user interface. Some of the time, depending on what the user enters, I want it to display a list of rows from the database, I was thinking of using the JList.
the current code to display to the labels is:
String sqlQuery = "select Column1, Column2, Column3, Column4, Column5 from APP.DATA123 " +
"where (Column1 = ?) AND (Column2 = ?) AND (Column3 = ?) OR (Column1 = ?) AND (Column2 = ?)";
String abc = jTextField2.getText();
String cba = (String)jComboBox1.getSelectedItem();
String cab = (String)jComboBox2.getSelectedItem();
String data = "jdbc:derby://localhost:1527/sample";
try (
Connection conn = DriverManager.getConnection(
data, "app", "app");
PreparedStatement st = conn.prepareStatement(sqlQuery)) {
Class.forName("org.apache.derby.jdbc.ClientDriver");
st.setString(1, abc);
st.setString(2, cba);
st.setString(3, cab);
st.setString(4, cba);
st.setString(5, cab);
ResultSet rec = st.executeQuery();
while (rec.next()) {
jLabel1.setText(rec.getString("Column1"));
jLabel2.setText(rec.getString("Column2"));
jLabel3.setText(rec.getString("Column3"));
jLabel4.setText(rec.getString("Column4"));
jLabel5.setText(rec.getString("Column5"));
}
st.close();
Is there an easier way to make it so that if there is more than one row of the database to be displayed to the user, I can make a JList so that all of the columns of one row (and possibly an image but I'll think about that later), are displayed as one item on the JList. So Columns1-5 are one JlistItem, and then columns 1-5 for the next database row are the next JList item etc?
Or another similar way that anyone knows of?
There is not that much text per column only about 5-15 characters.
You have to bind your JList to a ListModel implementation and fill that ListModel. In your case - each item in your ListModel is a concatenated string of all items from each row in ResultSet. Something like following :
DefaultListModel<String> model = new DefaultListModel<>();
JList list = new JList(model);
JScrollPane pane = new JScrollPane(list);//add the "pane" to your form next line
String abc = jTextField2.getText();
String cba = (String) jComboBox1.getSelectedItem();
String cab = (String) jComboBox2.getSelectedItem();
String data = "jdbc:derby://localhost:1527/sample";
try(
Connection conn = DriverManager.getConnection(
data, "app", "app");
PreparedStatement st = conn.prepareStatement(sqlQuery))
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
st.setString(1, "abc");
st.setString(2, "cba");
st.setString(3, "cab");
st.setString(4, "cba");
st.setString(5, "cab");
ResultSet rec = st.executeQuery();
// may want to make it constant (final static)
final String SPACE = " ";
StringBuilder sBuilder = new StringBuilder();
while (rec.next()) {
sBuilder.setLength(0);
sBuilder
.append(rec.getString("Column1")).append(SPACE)
.append(rec.getString("Column2")).append(SPACE)
.append(rec.getString("Column3")).append(SPACE)
.append(rec.getString("Column4")).append(SPACE)
.append(rec.getString("Column5")).append(SPACE);
model.addElement(sBuilder.toString());
}
st.close();
Take a look at this article, might be very helpful in your case. And, BTW, googling or reading docs is much faster than writing a question on SO and waiting for answer =). Cheers.

Insert values of arraylist into mysql table

I am trying to insert values from arraylist into mysql table.
List lstUnique=new ArrayList<Object>();
//code to feed the data into list from resultset.
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/MYdb","root","");
stmt=con.createStatement();
String sql1="select SourceFrom,Updated,Location_Type,Industry,ET_Rank,BT_Rank from mytable";
rs1=stmt.executeQuery(sql1);
rsmd=rs1.getMetaData();
columnNumber=rsmd.getColumnCount();
while(rs1.next()){
lstUnique.add(rs1.getString("SourceFrom")+","+rs1.getString("Updated")+","+rs1.getString("Location_Type")+","+
rs1.getString("Industry")+","+rs1.getString("ET_Rank")+","+rs1.getString("BT_Rank"));
}
String insertsql="";
String SourceFrom=lstUnique.get(0).toString(); //its first column of the table.
insertsql="Insert into java_uniquedata (SourceFrom,field2,field3,field4,field5) values(?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(insertsql);
//I tried this way also.
for(int i=0;i<lstUnique.size();i++){
SourceFrom=lstUnique.get(i).toString();
}
for(int i=0;i<lstUnique.size();i++){
System.out.println("\n" + lstUnique.get(i).toString());
}
rs1.close();
con.close();
}catch(Exception e){
System.out.println(e);
}
But I am getting error
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
My list has only one record in it, which has total 5 columns' values. Can you guide me how do I fetch values of first record from arraylist and insert it into mysql table.
You should separate the values for your insert statement. Either use a custom datastructure (class) or use a List<String>.
Something like this might work:
List<List<String>> lstUnique=new ArrayList<>(); // note the List of List
try {
/* ... your database query here ... */
while(rs1.next()){
List<String> values = new ArrayList<>(); // create list for values
values.add(rs1.getString("SourceFrom"));
values.add(rs1.getString("Updated"));
values.add(rs1.getString("Location_Type"));
values.add(rs1.getString("Industry"));
values.add(rs1.getString("ET_Rank"));
values.add(rs1.getString("BT_Rank"));
lstUnique.add(values); // add values for each row
}
String insertsql="Insert into java_uniquedata (SourceFrom,field2,field3,field4,field5) values(?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(insertsql);
for(List<String> values : lstUnique) { // use for each for rows
for(int i=0;i<values.size();i++) { // set argument values to prepared statement
ps.setString((i+1), values.get(i));
}
ps.execute(); // execute insert statement
}
ps.close();
} catch(Exception e){
System.out.println(e);
} finally { // close recordset and connection in finally-block! (or use 'try-with-resource'!)
rs1.close();
con.close();
}
try this one
for(int i=0; i < lstUnique.size();i++){
ps.setString(1, lstUnique.get(i).toString());
}
ps.execute(insertsql);
I tried this and it inserts data into database
ArrayList<String> lis = new ArrayList<String>();
lis.add("pare1");
lis.add("2");
//code to feed the data into list from resultset.
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "paresh");
String insertsql="";
insertsql="Insert into stud (name,age) VALUES (?,?)";
PreparedStatement ps=connection.prepareStatement(insertsql);
//this will set value for your insert statement
System.out.println(lis.get(0).toString());
ps.setString(1, lis.get(0).toString());
ps.setInt(2, Integer.parseInt(lis.get(1)));
System.out.println(ps);
ps.execute(insertsql);
Completely different aproach for a solution to the task, if it is not mandatory to be solved in Java(?):
Since your code sample gives the impression that you're reading from and writing to the same database, you might also consider to copy the data in-database using the SQL INSERT-SELECT Syntax:
INSERT INTO java_uniquedata (SourceFrom, field2, field3, field4, field5)
SELECT DISTINCT SourceFrom, Updated, Location_Type, Industry, ET_Rank, BT_Rank
FROM mytable;
See MySQL INSERT ... SELECT Syntax.

Java Incorrect syntax near '0'

I'm having problems trying to insert the values into my database.
When i do the code below it works
insertString = "insert into Players
values(1,'Fred','Fish','fredfish#gamer.net','Ithroeann',19770322)";
statement.executeUpdate(insertString);
but when I try to do this look here it gives me an incorrect syntax near '0' error
I'm trying to loop it to add it automatically through a file
Scanner input = new Scanner(new File("players.txt"));
while (input.hasNext()) {
String[] temp;
String str = input.next();
temp = str.split("\\|");
insertString = "insert into Players values(temp[0], temp[1],temp[2],temp[3],temp[4],temp[5])";
statement.executeUpdate(insertString);
}
This is a String. If you want to append elements of the temp array to the String, you can't do it this way.
You can do it like this :
insertString = "insert into Players values("+temp[0]+",'"+temp[1]+"','"+temp[2]+"','"+temp[3]+"','"+temp[4]+"',"+temp[5]+")";
statement.executeUpdate(insertString);
Of course using a PreparedStatement would be a much better solution.
PreparedStatement stmt = conn.prepareStatement("insert into Players values(?,?,?,?,?,?)");
stmt.setInt (1, Integer.parseInt(temp[0]));
stmt.setString (2, temp[1]);
stmt.setString (3, temp[2]);
stmt.setString (4, temp[3]);
stmt.setString (5, temp[4]);
stmt.setInt (6, Integer.parseInt(temp[5]));
stmt.executeUpdate();
Use a PreparedStatement to bind your query parameters as
PreparedStatement pStmt = connection.prepareStatement(
"insert into Players values (?, ?, ?, ?, ?, ?)");
// index starts from 1
int i = 1;
// bind first int value
pStmt.setInt(i, Integer.parseInt(temp[0]));
// bind string values
for (; i < temp.length; i++)
pStmt.setString(i, temp[i-1]);
// bind last int value
pStmt.setInt(i, Integer.parseInt(temp[i-1]));
// execute insert
pStmt.executeUpdate();
Unless the code posted above is partial, it seems like you're missing the statement preparation part. Try something like the following:
Scanner input = new Scanner(new File("players.txt"));
while (input.hasNext()) {
String[] temp;
String str = input.next();
temp = str.split("\\|");
dbConnection = getDBConnection(); // Implement this method based on your DB configuration
String insertString = "insert into Players values(?, ?, ? , ?, ?, ?)";
PreparedStatement statement = dbConnection.createStatement();
statement.setInt(temp[0]); // int, or whichever type you have
statement.setInt(temp[1]); // int, or whichever type you have
statement.setInt(temp[2]); // int, or whichever type you have
statement.setInt(temp[3]); // int, or whichever type you have
statement.setInt(temp[4]); // int, or whichever type you have
// ^ for the above, if all fields are the same - you can do this in a loop
statement.executeUpdate(insertTableSQL); // execute the insert

Categories