Retrieve auto_increment value of multiple rows from MySQL in batch mode - java

There is a mysql table with primary key as id int auto_increment,
I need to insert multiple rows in batch with multiple insert statement, with autocommit disabled, as following:
SET autocommit=0;
INSERT INTO dummy(NAME, `size`, create_date) VALUES('test', 1, NOW());
INSERT INTO dummy(NAME, `size`, create_date) VALUES('test', 2, NOW());
COMMIT;
Is it possible to get each generated id, instead of only the last id.
If yes, when was each id generated, and how to get all the ids via jdbc?
Thx.

If you want to retrieve the AUTO_INCREMENT keys via JDBC you need to use the JDBC features for doing so (RETURN_GENERATED_KEYS and .getGeneratedKeys()), like this:
try (Connection conn = DriverManager.getConnection(myConnectionString, "root", "beer")) {
try (Statement st = conn.createStatement()) {
st.execute(
"CREATE TEMPORARY TABLE dummy (" +
"`id` INT AUTO_INCREMENT PRIMARY KEY, " +
"`NAME` VARCHAR(50), " +
"`size` INT, " +
"`create_date` DATETIME " +
")");
}
conn.setAutoCommit(false);
System.out.println("AutoCommit is OFF.");
String sql = "INSERT INTO dummy(NAME, `size`, create_date) VALUES('test', ?, NOW())";
try (PreparedStatement ps = conn.prepareStatement(
sql,
PreparedStatement.RETURN_GENERATED_KEYS)) {
// first batch
ps.setInt(1, 1); // `size` = 1
ps.addBatch();
ps.setInt(1, 2); // `size` = 2
ps.addBatch();
ps.executeBatch();
System.out.println("First batch executed. The following AUTO_INCREMENT values were created:");
try (ResultSet rs = ps.getGeneratedKeys()) {
while (rs.next()) {
System.out.println(rs.getInt(1));
}
}
try (Statement st = conn.createStatement()) {
sql = "SELECT COUNT(*) AS n FROM dummy";
try (ResultSet rs = st.executeQuery(sql)) {
rs.next();
System.out.println(String.format("The table contains %d row(s).", rs.getInt(1)));
}
}
conn.rollback();
System.out.print("Transaction rolled back. ");
try (Statement st = conn.createStatement()) {
sql = "SELECT COUNT(*) AS n FROM dummy";
try (ResultSet rs = st.executeQuery(sql)) {
rs.next();
System.out.println(String.format("The table contains %d row(s).", rs.getInt(1)));
}
}
// second batch
ps.setInt(1, 97); // `size` = 97
ps.addBatch();
ps.setInt(1, 98); // `size` = 98
ps.addBatch();
ps.setInt(1, 99); // `size` = 99
ps.addBatch();
ps.executeBatch();
System.out.println("Second batch executed. The following AUTO_INCREMENT values were created:");
try (ResultSet rs = ps.getGeneratedKeys()) {
while (rs.next()) {
System.out.println(rs.getInt(1));
}
}
}
try (Statement st = conn.createStatement()) {
sql = "SELECT COUNT(*) AS n FROM dummy";
try (ResultSet rs = st.executeQuery(sql)) {
rs.next();
System.out.println(String.format("The table contains %d row(s).", rs.getInt(1)));
}
}
}
... which produces the following console output:
AutoCommit is OFF.
First batch executed. The following AUTO_INCREMENT values were created:
1
2
The table contains 2 row(s).
Transaction rolled back. The table contains 0 row(s).
Second batch executed. The following AUTO_INCREMENT values were created:
3
4
5
The table contains 3 row(s).

Related

why I cannot sum all number between two rows?

I am trying to write a code that sum all the data in a column named AMOUNT between two rows in a column named DATA in a table named PERSON and I used the sum function and I use between function
and I got the following error:
java.sql.SQLSyntaxErrorException: Syntax error:
Encountered "BETWEEN" at line 1, column 45.
the code :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
String sql = "SELECT SUM(AMOUNT) AS SUMAMOUNT " +
"FROM PERSON BETWEEN DATE=? AND DATE=?";
con = DriverManager.getConnection("jdbc:derby://localhost:1527/Invoices",
"user1", "password");
ps = con.prepareStatement(sql);
ps.setString(1, jTextField1.getText());
ps.setString(2, jTextField2.getText());
rs = ps.executeQuery();
if (rs.next()) {
String sum = rs.getString("sumAmount");
jLabel3.setText(sum);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
Try something like this:
String sql = "SELECT SUM(AMOUNT) AS SUMAMOUNT FROM PERSON " +
"WHERE (col_name) between '2020-05-01 00:58:26' " +
"and '2021-06-18 19:53:17'";

Invalid column index error oracle db java

I have simple program that works with mysql db. I need to switch to oracle db.
I am trying to insert data into database but I'm getting this error. I tried manually to insert data everyting is fine but programatically I got error.
This is my code.
public void saveHasta(List<Hasta> hastaList) {
try {
// PreparedStatement stmt = connection.prepareStatement("INSERT INTO tblHasta (hasta_tc_kimlik,hasta_isim, hasta_soyisim,hasta_dogum_tarih,hasta_meslek,randevu_ID) VALUES (12345678912, 'Mert', 'Akel', '1995-07-21', 'Yazilim', 2)");
//
// System.out.println("Oldu");
PreparedStatement stmt = connection.prepareStatement("INSERT INTO tblHasta (hasta_tc_kimlik,hasta_isim, hasta_soyisim,hasta_dogum_tarih,hasta_meslek,randevu_ID) VALUES (?,'?','?','?','?',?)");
Iterator<Hasta> it = hastaList.iterator();
while (it.hasNext()) {
Hasta h = it.next();
stmt.setLong(1, h.getTcKimlik());
stmt.setString(2, h.getIsim());
stmt.setString(3, h.getSoyIsim());
stmt.setString(4, h.getDogumTarih());
stmt.setString(5, h.getMeslek());
PreparedStatement pst = connection.prepareStatement(
"SELECT randevu_ID FROM tblRandevu where tc_kimlik = '" + h.getTcKimlik() + "'");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
randevu_id = rs.getInt("randevu_ID");
}
stmt.setInt(6, randevu_id);
stmt.addBatch();
}
stmt.executeUpdate();
System.out.println("Oldu");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is my table
CREATE TABLE tblhasta
( hasta_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1) NOT NULL,
hasta_tc_kimlik INTEGER,
hasta_isim varchar2(50),
hasta_soyisim varchar2(50),
hasta_dogum_tarih varchar2(50),
hasta_meslek varchar2(50),
randevu_ID INTEGER,
CONSTRAINT hasta_pk PRIMARY KEY (hasta_ID)
);
You have used the prepared statements in a wrong way
PreparedStatement stmt = connection.prepareStatement("INSERT INTO tblHasta (hasta_tc_kimlik,hasta_isim, hasta_soyisim,hasta_dogum_tarih,hasta_meslek,randevu_ID)
VALUES (?,'?','?','?','?',?)");
Change values to
PreparedStatement stmt = connection.prepareStatement("INSERT INTO tblHasta (hasta_tc_kimlik,hasta_isim, hasta_soyisim,hasta_dogum_tarih,hasta_meslek,randevu_ID)
VALUES (?,?,?,?,?,?)");

Invalid column index for JDBC insert with sequence number

Below is my code:
I'm passing three parameters to method insertRecordIntoTable which will execute JDBC insert query but I'm receiving Invalid column index.
Below are log statements which got printed:
Inside insertRecordIntoTable
ID from sequence 14
Invalid column index
private static void insertRecordIntoTable(String userName, String targetEmail, String siteName) throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
System.out.println("Inside insertRecordIntoTable ");
String insertTableSQL = "insert into TableName values(?,?,?,?,?)";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(insertTableSQL);
ResultSet srs = preparedStatement.executeQuery("SELECT id_seq.NEXTVAL FROM dual");
if ( srs!=null && srs.next() ) {
int myId = srs.getInt(1);
System.out.println("ID from sequence "+myId);
preparedStatement.setInt(1, myId);
System.out.println("Inserted ID value "+myId);
srs.close();
}
preparedStatement.setString(2, userName);
System.out.println("Inserted username value "+userName);
preparedStatement.setString(3, targetEmail);
System.out.println("Inserted targetEmail value "+targetEmail);
preparedStatement.setString(4, siteName);
System.out.println("Inserted sitecode value "+siteName);
preparedStatement.setTimestamp(5, getCurrentTimeStamp());
System.out.println("Inserted date value "+getCurrentTimeStamp());
preparedStatement .executeUpdate();
System.out.println("Inserted values ");
System.out.println("Inserted name & email into the table...");
// execute insert SQL stetement
preparedStatement.executeUpdate();
System.out.println("Record is inserted into DBUSER table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
You are using the same PreparedStatement variable twice
preparedStatement.executeQuery("SELECT id_....);
Create and use another variable for this Query else the original Query will be overwritten.
Also consider what is going to happen if
if ( srs!=null && srs.next() ) {
returns false

Java ResultSet Column count is always 1

I want to show the Column numbers of a table but it always shows the number 1. I have written the code below:
Class.forName(JDBC_DRIVER);
java.sql.Connection con=DriverManager.getConnection(DB_URL,USER,PASS);
try (Statement stmt = (Statement) con.createStatement()) {
String sql;
sql = "SELECT count(*) FROM information_schema.columns WHERE
table_name=\"my_b\"";
try (
ResultSet rs = stmt.executeQuery(sql)) {
int columCount = rs.getMetaData().getColumnCount();
System.out.println("Column number is: "+columCount);
}
stmt.close();
con.close();
Where is the error ?
First, you haven't needed Class.forName to load your JDBC drivers in a long time. Second, you are selecting a value but you are reading metadata. Third, when using try-with-resources you don't need explicit close calls (and your Connection should be closed in a finally, for example). Finally, use PreparedStatement and bind parameters. Like,
java.sql.Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
String query = "SELECT count(*) FROM information_schema.columns WHERE table_name=?";
try (PreparedStatement stmt = con.prepareStatement(query)) {
stmt.setString(1, "my_b");
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
int columCount = rs.getInt(1);
System.out.println("Column number is: " + columCount);
} else {
System.out.println("No rows");
}
}
} finally {
con.close();
}
You are not retrieving the result of the query, instead you are asking the result set metadata how many columns the result set has. And as your query only produce a single column (ie COUNT(*)), the result of ResultSetMetaData.getColumnCount() is 1, and that value is correct.
If you want to get the result of the query, you need to get it from the result set:
try (ResultSet rs = stmt.executeQuery(sql)) {
if (rs.next()) {
int columnsNumber = rs.getInt(1);
System.out.println("Column number is: "+columnsNumber );
}
}
The problem is that ResultSet.getColumnCount returns the number of columns in the query's result set, not the number of columns in a table.
If you are trying to get a count of columns on a table, the query you have is correct. You just need to retrieve the result of the query, rather than its metadata.
String sql = "SELECT count(*) FROM information_schema.columns WHERE table_name=\"my_b\"";
try (
ResultSet rs = stmt.executeQuery(sql));
rs.next();
int columCount = rs.getInt(1);
System.out.println("Column number is: " + columCount);
}
Class.forName(JDBC_DRIVER);
java.sql.Connection con=DriverManager.getConnection(DB_URL,USER,PASS);
try (Statement stmt = (Statement) con.createStatement()) {
String sql = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'database_name' AND table_name = 'table_name'"
try (
ResultSet rs = stmt.executeQuery(sql)) {
//int columCount = rs.getMetaData().getColumnCount();
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
System.out.println("Column number is: "+columnsNumber );
}
stmt.close();
con.close();
Try SELECT * FROM information_schema.columns WHERE table_name=\"my_b\"
Just omit the count(*) since this returns a single result, while you are looking for all columns.

How to use dynamic table name in SELECT query using JDBC

I have 5 or table table to query from \
my syntax i like this
String sql2 = "SELECT * FROM ? WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql2);
System.out.println("SQL before values are set "+sql2);
System.out.println("The values of table/test name recieved in TestPrint stage 1 "+tblName);
System.out.println("The values of test name recieved in TestPrint stage 1 "+key);
// values are outputted correctly but are not getting set in the query
pst.setString(1, tblName);
pst.setLong(2, key);
ResultSet rs2 = pst.executeQuery(sql2);
while(rs2.next()){
String ID = rs2.getString("ID");
jLabel35.setText(ID);
jLabel37.setText(ID);
jLabel38.setText(ID);
// them print command is initiated to print the panel
}
The problem is when i run this i get an error saying ".....you have and error in SQL syntax near ? WHERE Patient_ID = ?"
When i output the sql using system.out.println(sql2);
values are not set in sql2
When you prepare a statement, the database constructs an execution plan, which it cannot do if the table is not there. In other words, placehodlers can only be used for values, not for object names or reserved words. You'd have to rely on Java to construct your string in such a case:
String sql = "SELECT * FROM `" + tblName + "` WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql);
pst.setLong(1, key);
ResultSet rs = pst.executeQuery();
String sqlStatment = "SELECT * FROM " + tableName + " WHERE Patient_ID = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sqlStatment);
preparedStatement.setint(1, patientId);
ResultSet resultSet = preparedStatement.executeQuery();
public void getByIdEmployer() throws SQLException {
Connection con = null;
try {
con = jdbcUtil.connectionDtls();
PreparedStatement ptst = con.prepareStatement(getById);
ptst.setInt(1, 4);
ResultSet res = ptst.executeQuery();
while (res.next()) {
int empid = res.getInt(1);
System.out.println(empid);
String name = res.getString(2);
System.out.println(name);
int salary = res.getInt(3);
System.out.println(salary);
String location = res.getString(4);
System.out.println(location);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
con.close();
}
}

Categories

Resources