How to get the final batch SQL query from Spring boot SQL statement. I am connecting to PostgreSQL database with Java 8 and spring boot.
String sqlQuery = "insert into table1 (id, name) values (?, ?)";
PreparedStatement pstmt = connection.prepareStatement(sqlQuery);
pstmt.setInt(1, 1);
pstmt.setString(2, "name1");
pstmt.addBatch();
pstmt.setInt(1, 2);
pstmt.setString(2, "name2");
pstmt.addBatch();
pstmt.executeBatch();
System.out.println(pstmt);
Output:
insert into table1 (id, name) values (2, name2)
Expected Output:
insert into table1 (id, name) values (1, name1), (2, name2)
I am getting the last SQL query instead of the batch SQL query.
Related
Is there any possibility to specify the sequence generator as a value for a column in SimpleJdbcInsert, JdbcTemplate, NamedParameterJdbcTemplate or any other class for batch execution?
e.g., I want to achieve the SQL to be generated by any of the above classes as:
INSERT INTO SOME_TABLE_NAME (ID, COLUMN_A,...) VALUES (SOME_SEQUENCE.NEXTVAL, 'value for column A', ...);
A sample code snippet is like:
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
List<SomeTableEntity> listOfEntities; // received from method parameter
SimpleJdbcInsert sql = new SimpleJdbcInsert(dataSource).withTableName("SOME_TABLE_NAME");
SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(listOfEntities.toArray());
sql.executeBatch(batch);
I tried to trick the SimpleJdbcInsert as:
SqlParameterSource id = new MapSqlParameterSource("ID", "SOME_SEQUENCE.nextval"));
SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(listOfEntities.toArray());
List<SqlParameterSource> params = new ArrayList<>(batch.length + 1);
params.add(id);
for (SqlParameterSource param : batch)
{
params.add(param);
}
sql.executeBatch(params.toArray(new SqlParameterSource[] {}));
But not to a surprise, that didn't worked since the ID column is of type numeric and it tried to fill the value as "SOME_SEQUENCE.nextval" instead of evaluating the result of SOME_SEQUENCE.nextval.
PS: There are too many columns in the table and due to that I do not want to use a prepared statement solution
String sql = "INSERT INTO USER
(USER_PK, ACCOUNTNUMBER, FIRSTNAME, LASTNAME, EMAIL )
VALUES
(user.nextval, ?, ?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, accountNumber);
ps.setString(2, firstName);
ps.setString(3, lastName);
ps.setString(4, email);
I want to insert 5 datas into one SQL table, the last four of which are already working and fine, but the first one should be from another table, a String, giving an Int to the table in which im inserting it. And this is my solution so far. However i'm still getting an error:
"The index 5 is out of range."
PreparedStatement stmt = connection.prepareStatement("INSERT INTO RECORDS (LocationId, RecId, RecValues, YearTime, HourTime) VALUES " +
"((SELECT LocationId from Locations where Location_name = 'Mic HR1'), ?, ?, ?, ?)");
stmt.setInt(1,1);
stmt.setInt(2, recid);
stmt.setInt(3, inputData);
stmt.setDate(4, sqlDate);
stmt.setTime(5, Time.valueOf(dtf.format(now)));
stmt.executeUpdate();
Actually you have only four parameters defined on your query, because LocationId is being calculated by the inner select you provided. That's why you are getting the error.
Try this:
PreparedStatement stmt = connection.prepareStatement("INSERT INTO RECORDS (LocationId, RecId, RecValues, YearTime, HourTime) VALUES " +
"((SELECT LocationId from Locations where Location_name = 'Mic HR1'), ?, ?, ?, ?)");
stmt.setInt(1, recid);
stmt.setInt(2, inputData);
stmt.setDate(3, sqlDate);
stmt.setTime(4, Time.valueOf(dtf.format(now)));
stmt.executeUpdate();
I'm having trouble inserting a row into a MySQL table with Java. I'm not sure what the problem is as it isn't giving an error. I'm trying to insert the row with the following:
String sql = "INSERT INTO users (uuid, authKey, code, scratches) VALUES (?, ?, ?, ?);";
PreparedStatement insertStmt = connection.prepareStatement(sql);
insertStmt.setString(1, uuid);
insertStmt.setString(2, key);
insertStmt.setInt(3, code);
insertStmt.setString(4, getScratchString());
insertStmt.executeUpdate();
The table 'users' is created successfully with no errors with the following:
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS users (uuid VARCHAR(40), authKey VARCHAR(30), code INT(10), scratches VARCHAR(45));");
When trying to insert the row with the same update in phpmyadmin, it works fine. There is no error given by the update so I have no idea where to start debugging. Any help would be appreciated. Thanks.
You have to do commit transaction check the below code
String sql = "INSERT INTO users (uuid, authKey, code, scratches) VALUES (?, ?, ?, ?)";
PreparedStatement insertStmt = connection.prepareStatement(sql);
insertStmt.setString(1, uuid);
insertStmt.setString(2, key);
insertStmt.setInt(3, code);
insertStmt.setString(4, getScratchString());
insertStmt.executeUpdate();
connection.commit();
I'm currently facing a problem with my SQL query using a prepared statement.
String test= "INSERT INTO TEST" + "(ID, IC, CN, CT, Time)"
+ "VALUES ('"+ ID +"','"+ IC +"','"+CN +"','"+ CT +"','"+ time +"')";
preparedStatement = myConn.prepareStatement(test);
preparedStatement.executeUpdate();
I have successfully connected to the database, and the table is created out. Is it because of the single quotation problem?
You're missing the point of using a PreparedStatement. You could just bind the values so you don't have to mess around with quoting yourself:
String test= "INSERT INTO TEST (ID, IC, CN, CT, Time) VALUES (?, ?, ?, ?, ?)";
preparedStatement = myConn.prepareStatement(test);
preparedStatement.setString(id);
preparedStatement.setString(ic);
preparedStatement.setString(cn);
preparedStatement.setString(ct);
preparedStatement.setDate(new Timestamp(time));
preparedStatement.executeUpdate();
I am using eclipse to insert data into MySQL, and it is only inserting the last row of the data.
String countryCodeSql = "INSERT INTO session" + "(sessionTimestamp,countryCode,countryName,visitorID)" + "VALUES ('"+timeStamp+"','"+countryCode+"','" + countryName+"','" + visitorID+"')";
myStat.executeUpdate(countryCodeSql);
these are my lines of codes, but I think it should be working fine as the codes below worked and the data were inserted.
String timeStampSql = "INSERT INTO conversation" + "(timestamp)" + "VALUES ('" +timeStamp+"')";
myStat.executeUpdate(timeStampSql);
You can use the preparedStatement to insert data in the database when the data are dynamic. here is an example:
Connection connection = DriverManager.getConnection(DATABASE_URL,USERNAME,PASSWORD);
String query = "INSERT INTO session (sessionTimestamp,countryCode,countryName,visitorID) values(?,?,?,?)";
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setString (1, timeStamp);
preparedStmt.setString (2, countryCode);
preparedStmt.setString (3, countryName);
preparedStmt.setString (4, visitorID);
preparedStmt.execute();