This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 5 years ago.
I'm using H2DB for a litthe cuesheet-database. I'm inserting several records to a table with anj auto-increment field for the primary key ID. For each record I want to know the value of the ID-field after insert, i.e. before committing. How do I get this value?
In short:
use Statement.RETURN_GENERATED_KEYS as second parameter when preparing the insert statement
get ResultSet from statement after insert with .getGeneratedKeys()
get generated id from ResultSet
This should also work when using transactions.
The following example demonstrates this:
try {
// register driver
Class.forName("org.h2.Driver");
// open connection, in-memory database
Connection conn = DriverManager.getConnection("jdbc:h2:mem:");
conn.setAutoCommit(false);
// create table
PreparedStatement createSample = conn.prepareStatement("CREATE TABLE sample (id int not null auto_increment, txt varchar(128))");
createSample.executeUpdate();
createSample.close();
// prepare insert statement
PreparedStatement insertStatement = conn.prepareStatement("INSERT INTO sample (txt) VALUES (?)", Statement.RETURN_GENERATED_KEYS);
// dummy list with texts
List<String> dummyTexts = Arrays.asList("Entry A", "Entry B", "Entry C", "Entry D", "Entry E");
// insert data
for (String dummyText : dummyTexts) {
insertStatement.setString(1, dummyText);
insertStatement.executeUpdate();
// get generated key
ResultSet generatedKeys = insertStatement.getGeneratedKeys();
if ((generatedKeys != null) && (generatedKeys.next())) {
int generatedKey = generatedKeys.getInt(1);
System.out.println("generated key " + generatedKey + " for entry '" + dummyText + "'");
}
}
// commit
conn.commit();
insertStatement.close();
// select data
PreparedStatement selection = conn.prepareStatement("SELECT id, txt FROM sample");
ResultSet selectionResult = selection.executeQuery();
while (selectionResult.next()) {
System.out.println("id: " + selectionResult.getInt(1) + ", txt: '" + selectionResult.getString(2) + "'");
}
selectionResult.close();
selection.close();
// close connection
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
Related
This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 6 days ago.
Here is my code:
String sql="INSERT INTO ventas(prefijo,fecha,hora,vtanum,vlrfactura,cambio) VALUES(?,?,?,?,?,?);";
try {
ps=con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
ps.setString(1, vta.getPrefijo());
ps.setDate(2, vta.getFecha());
ps.setTime(3, vta.getHora());
ps.setInt(4, vta.getVtanum());
ps.setInt(5,vta.getVlrfactura());
ps.setInt(6,vta.getCambio());
ps.execute();
return true;
} catch (SQLException ex) {
Logger.getLogger(OperacionesBD.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
I want get the PK of that sentence and then use it in another statement like this:
SET #last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO pagmundimotos.pagos(id_venta,frmpag) VALUES (#last_id_in_table1, '9');
But I don't know how to obtain the last_insert_id in Java.
Use ResultSet object to fetch the GeneratedKeys on Statement
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
long id = rs.getLong(1);
System.out.println("Inserted ID -" + id); // display inserted record
}
For Oracle :
String key[] = {"ID"}; //put the name of the primary key column
ps = con.prepareStatement(insertQuery, key);
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if (rs.next()) {
generatedKey = rs.getLong(1);
}
I have the list of id's as follows '01/A', '02/B', '03/C', '04/D', '05/E'
MASTER TABLE
ID
STATUS
02/B
NA
03/C
A
05/E
A
MASTER table I have the status of the above id's from conB Database. If id's are present in MASTER table, then I need to pick the status from MASTER table and insert into TEMP table in conA Database.
Note : 1st id : '01/A' and 4th id: '04/D' is not present in MASTER table.
So my code should skip those two id's and pick the status of other id's and insert into TEMP table.But I am getting and error message as "Invalid operation: result set is closed. ERRORCODE=-4470, SQLSTATE=null" at rs.next()
I am not sure where it went wrong. Anybody can help me out with this issue.
public int insertData(List<String> idList, Connection conA, Connection conB, )
throws SQLException, SQLTransientConnectionException, Exception {
int insertStatus = 0;
String id = null;
for (int i = 0; i < idList.size(); i++) {
String sql = "SELECT * FROM MASTER WHERE ID LIKE '%" + idList.get(i) + "%')";
PreparedStatement ps = conB.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) { // Invalid operation: result set is closed. ERRORCODE=-4470, SQLSTATE=null
try {
id = rs.getString("ID");
status = rs.getString("STATUS");
String sql1 = "INSERT INTO TEMP (ID, STATUS) VALUES ('" + id + "','" + status + "')";
PreparedStatement ps1 = conA.prepareStatement(sql1);
insertStatus = ps1.executeUpdate();
ps1.close();
log.info("Number of rows inserted " + insertStatus);
} catch (SQLException e) {
e.printStackTrace();
}
}
ps.close();
rs.close();
}
return insertStatus;
}
I'm creating a desktop App where user can import file and retrieve them from database (SQlite) and them see or modify data
So if someone can help me with all this
1.I created database using SQLITE
2.I used button for filechooser then A button save for import to database
Problems
1. Open file (done)
2.saving into database (No)
U can see my code
Mycode open button
public void openfolder (ActionEvent event) throws IOException {
FileChooser fc = new FileChooser();
fc.setInitialDirectory(new File("C:\\Users\\Lenovo\\Documents\\NetBeansProjects\\sogece\\src\\PDFimport"));
fc.getExtensionFilters().addAll(
new ExtensionFilter("PDF Files","*.PDF"));
List<File> selectedFiles = fc.showOpenMultipleDialog(null);
if (selectedFiles !=null){
for(int i =0;i <selectedFiles.size();i++){
listview.getItems().add(selectedFiles.get(i) .getAbsolutePath());
}}else{
System.out.println("file is not valid");
}}
Mycode save button
String query = "INSERT INTO PDFS (liste) VALUES (" + listview.getAccessibleText()
+ ")";
System.out.println("Inserting\n" + query);
insertStatement(query);
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:sogeclair.sqlite");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
stmt.close();
c.commit();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getField(query) + ": " + e.getMessage());
System.exit(0);
}
and the error
Inserting
INSERT INTO PDFS (liste) VALUES (null)
Opened database successfully
Our query was: INSERT INTO PDFS (liste) VALUES (null)
Opened database successfully
Deleting directory
C:\Users\Lenovo\Documents\NetBeansProjects\sogece\dist\run674970846
Then I used another solution for Import PDF but I got this as ERROR
Code
String query = "INSERT INTO PDFS (liste) VALUES (?) "try (PreparedStatement stm = connection.prepareStatement(query) {
//NOTE: Position indexes start at 1, not 0
stm.setString(1, listview.getAccessibleText ());
stm.executeUpdate();
}
error
java.lang.UnsupportedOperationException: Not supported yet. at sogeclair.connection.prepareStatement(connection.java:17) at sogeclair.PlanningController.btninsert(PlanningController.java:285) ... 58.
I went Back to verify the problem but I didn't understand what does it mean
Connection.java :17
class connection { static PreparedStatement prepareStatement(String query) { throw new UnsupportedOperationException("Not supported yet.");
PlanningController.java:285 :try (PreparedStatement stm = connection.prepareStatement(query))
Change this:
String query = "INSERT INTO PDFS (liste) VALUES (" +listview.getAccessibleText ()+ ")";
To this :
String query = "INSERT INTO PDFS (liste) VALUES ('" +listview.getAccessibleText ()+ "')";
VARCHAR type should between two ''
Note
This can cause a syntax error or SQL Injection instead you have to use PreparedStatement
String query = "INSERT INTO PDFS (liste) VALUES (?)";
try (PreparedStatement stm = connection.prepareStatement(query) {
//NOTE: Position indexes start at 1, not 0
stm.setString(1, listview.getAccessibleText ());
stm.executeUpdate();
}
its duplicate question with Get last inserted auto increment id in mysql
I'm creating a group it insert on M_GROUPS.
M_GROUPS table:
GROUP_ID INT AUTO_INCREMENT,
GROUP_CREATOR_ID INT
which from session.
I need to take GROUP_ID and GROUP_CREATOR_ID and insert it on
M_GROUP_MEMBERS table as
GROUP_ID INT,
MEMBER_ID INT.
My problem is I can't take auto increment value GROUP_ID from M_GROUPS
public void groupCreation(String groupname, int grouptype, int creator_id) {
DatabaseService oDatabaseService = new DatabaseService();
Connection connection = oDatabaseService.connect();
try {
Statement stmt = null;
stmt = connection.createStatement();
String sql;
sql = "INSERT INTO M_GROUPS( GROUP_NAME, GROUP_CREATOR_ID,
GROUP_TYPE, CREATION_TIME)"
+ " VALUES ('"
+ groupname
+ "','"
+ creator_id
+ "','"
+ grouptype + "',NOW())";
//stmt.executeUpdate(sql);
stmt.executeUpdate(sql);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (connection != null)
connection.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
Use getGeneratedKeys() method from your Statement object to identify the new auto generated values. Iterate the returned ResultSet object to get the newly generated key values in the order of batch statements.
Change:
stmt.executeUpdate(sql);
To:
int rowsAffected =
stmt.executeUpdate( sql, Statement.RETURN_GENERATED_KEYS );
ResultSet rs = stmt.getGeneratedKeys();
//******************************************************
// in case of batch insert, you can check how many are inserted
rs.last();
int rows = rs.getRow();
System.out.println( "Generated keys count: " + rows );
//******************************************************/
int currentRow = 1;
rs.beforeFirst();
while( rs.next() ) {
System.out.println( /**/( currentRow++ ) + " = " + /**/rs.getInt( 1 ) );
} // while rs
Once you have this auto generated key value in a variable, you can use it with other SQL statements, to store in other tables.
Note: Call to getGeneratedKeys() may throw java.sql.SQLFeatureNotSupportedException, if the JDBC driver, that you are using, does not support this method.
I am using hadoop-1.0.4 and hive-0.10.0 in redhat5. Service start successfully. I am able to create, drop, select table easily but I don't know how to insert data.
For example I have two text box and on button click I want to store data in table (userInfo). I have no clue how to store textbox vaue in userInfo(id,password).
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000/enggheads","", "");
Statement stmt = con.createStatement();
String tableName = "testHiveDriverTable";
stmt.executeQuery("drop table " + tableName);
ResultSet res = stmt.executeQuery("create table " + tableName + " (key int, value string)");
// show tables
String sql = "show tables '" + tableName + "'";
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
if (res.next()) {
System.out.println(res.getString(1));
}
It's Java, but I don't know how to insert two field value because Hive insertion is different than MySQL or other database syntax.
Create a dummy table in hive like below
create table dummy(dummy string) location '/path';
Above path will have a file which contains data X
Now run insert query from jdbc driver like below.
insert into table tblname select forntendvalue1,frontendvalue2 from dual;