I am trying to get the mysql command like mysql_insert_id(); which retrieve the last inserted row's auto_increment id. What can I do to get it in Java?
rs = st.executeQuery("select last_insert_id() from schedule");
lastid = rs.getString("last_insert_id()");
my lastid was declared as INT. I dono what to use in rs.get and also the parameter..
Using JDBC, you can use Connection.PreparedStatement(query, int) method.
PreparedStatement pstmt = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS);
pstmt.executeUpdate();
ResultSet keys = pstmt.getGeneratedKeys();
keys.next();
key = keys.getInt(1);
Try using an alias
rs = st.executeQuery("select last_insert_id() as last_id from schedule");
lastid = rs.getString("last_id");
see this post for answer & explanation
Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
risultato=rs.getInt(1);
}
Why not
SELECT MAX(id) FROM schedule
If id your column has a different name than id, you need to replace it accordingly in the above query.
You can use it like:
rs = st.executeQuery("SELECT MAX(id) AS id FROM schedule");
int lastid = rs.getInt("id");
You can use following query to get last auto_incremented ID of last inserted row.
SELECT (max(auto_incr_id)) from table_name;
Another option:
SELECT id FROM table_name ORDER BY id DESC LIMIT 1;
another way:
ResultSet rs = stmt.executeQuery("SELECT last_insert_id()");
while(rs.next()){
System.out.println("id = " + rs.getLong(1));
}
Related
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.
Is there a way to retrieve the auto generated key from a DB query when using a java query with prepared statements.
For example, I know AutoGeneratedKeys can work as follows.
stmt = conn.createStatement();
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
However. What if I want to do an insert with a prepared Statement.
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql);
//this is an error
stmt.executeUpdate(Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
//this is an error since the above is an error
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
Is there a way to do this that I don't know about. It seems from the javadoc that PreparedStatements can't return the Auto Generated ID.
Yes. See here. Section 7.1.9. Change your code to:
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.executeUpdate();
if(returnLastInsertId) {
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
There's a couple of ways, and it seems different jdbc drivers handles things a bit different, or not at all in some cases(some will only give you autogenerated primary keys, not other columns) but the basic forms are
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
Or use this form:
String autogenColumns[] = {"column1","column2"};
stmt = conn.prepareStatement(sql, autogenColumns)
Yes, There is a way. I just found this hiding in the java doc.
They way is to pass the AutoGeneratedKeys id as follows
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
I'm one of those that surfed through a few threads looking for solution of this issue ... and finally get it to work. FOR THOSE USING jdbc:oracle:thin: with ojdbc6.jar PLEASE TAKE NOTE:
You can use either methods:
(Method 1)
Try{
String yourSQL="insert into Table1(Id,Col2,Col3) values(SEQ.nextval,?,?)";
myPrepStatement = <Connection>.prepareStatement(yourSQL, Statement.RETURN_GENERATED_KEYS);
myPrepStatement.setInt(1, 123);
myPrepStatement.setInt(2, 123);
myPrepStatement.executeUpdate();
ResultSet rs = getGeneratedKeys;
if(rs.next()) {
java.sql.RowId rid=rs.getRowId(1);
//what you get is only a RowId ref, try make use of it anyway U could think of
System.out.println(rid);
}
} catch (SQLException e) {
//
}
(Method 2)
Try{
String yourSQL="insert into Table1(Id,Col2,Col3) values(SEQ.nextval,?,?)";
//IMPORTANT: here's where other threads don tell U, you need to list ALL cols
//mentioned in your query in the array
myPrepStatement = <Connection>.prepareStatement(yourSQL, new String[]{"Id","Col2","Col3"});
myPrepStatement.setInt(1, 123);
myPrepStatement.setInt(2, 123);
myPrepStatement.executeUpdate();
ResultSet rs = getGeneratedKeys;
if(rs.next()) {
//In this exp, the autoKey val is in 1st col
int id=rs.getLong(1);
//now this's a real value of col Id
System.out.println(id);
}
} catch (SQLException e) {
//
}
Basically, try not used Method1 if you just want the value of SEQ.Nextval, b'cse it just return the RowID ref that you may cracked your head finding way to make use of it, which also don fit all data type you tried casting it to! This may works fine (return actual val) in MySQL, DB2 but not in Oracle.
AND, turn off your SQL Developer, Toad or any client which use the same login session to do INSERT when you're debugging. It MAY not affect you every time (debugging call) ... until you find your apps freeze without exception for some time. Yes ... halt without exception!
Connection connection=null;
int generatedkey=0;
PreparedStatement pstmt=connection.prepareStatement("Your insert query");
ResultSet rs=pstmt.getGeneratedKeys();
if (rs.next()) {
generatedkey=rs.getInt(1);
System.out.println("Auto Generated Primary Key " + generatedkey);
}
How to get the outcome of the query-- the AVG(DIST).
MySQL is showing this result under the column "AVG(DIST)"-- no other clue.
How do i read this value from the ResultSet instance (rs in below code)?
PreparedStatement ps = c.prepareStatement("SELECT AVG(DIST) FROM POOL_TABLE");
ResultSet rs = ps.executeQuery();
ResultSet seems to be referring to them all by column names.
Not well-familiar to JDBC -- yet!
TIA.
You can use an alias name in the query and retrieve the value in any of the two ways.!
PreparedStatement ps = c.prepareStatement("SELECT AVG(DIST) AS AVERAGE_ALIAS FROM POOL_TABLE");
ResultSet rs = ps.executeQuery();
double avg = 0;
while (rs.next()) {
avg = rs.getDouble(1);
// OR
avg= rs.getDouble("AVERAGE_ALIAS");
}
Here it is:
double avg = 0;
while (rs.next()) {
avg = rs.getDouble(1);
}
Use alias if you have many aggregate functions in your query. See below answer!
PreparedStatement used for inserting of data,
i think you should use Statement.
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT AVG(DIST) FROM POOL_TABLE");
if( rs.next() ){
System.out.print( rs.getString(1) );
}
i hope this example would help you :)
I am passing the following query to a ResultSet object:
String query = "SELECT COUNT( DISTINCT KEY ), SOURCE FROM MY_TBL\n" +
"GROUP BY SOURCE\n" +
"ORDER BY SOURCE";
I want to capture the counts I am getting for each SOURCE and sum them into a total. How can I capture these counts via ResultSet since COUNT isn't a column name in the ResultSet and I don't think I can return it's value via rs.getInt("COUNT")?
getInt is overloaded, use index (an int) instead of a column name:
rs.getInt(1); // the first column is 1
Try having alias
String query = "SELECT COUNT( DISTINCT KEY ) AS COUNT, SOURCE FROM MY_TBL\n" +
"GROUP BY SOURCE\n" +
"ORDER BY SOURCE";
I Think it is better to use
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * from Customer");
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
I think "getColumnCount" retinto number of column in a table instead of number of rows...
This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 7 years ago.
Is there some way to get a value from the last inserted row?
I am inserting a row where the PK will automatically increase, and I would like to get this PK. Only the PK is guaranteed to be unique in the table.
I am using Java with a JDBC and PostgreSQL.
With PostgreSQL you can do it via the RETURNING keyword:
PostgresSQL - RETURNING
INSERT INTO mytable( field_1, field_2,... )
VALUES ( value_1, value_2 ) RETURNING anyfield
It will return the value of "anyfield". "anyfield" may be a sequence or not.
To use it with JDBC, do:
ResultSet rs = statement.executeQuery("INSERT ... RETURNING ID");
rs.next();
rs.getInt(1);
See the API docs for java.sql.Statement.
Basically, when you call executeUpdate() or executeQuery(), use the Statement.RETURN_GENERATED_KEYS constant. You can then call getGeneratedKeys to get the auto-generated keys of all rows created by that execution. (Assuming your JDBC driver provides it.)
It goes something along the lines of this:
Statement stmt = conn.createStatement();
stmt.execute(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet keyset = stmt.getGeneratedKeys();
If you're using JDBC 3.0, then you can get the value of the PK as soon as you inserted it.
Here's an article that talks about how : https://www.ibm.com/developerworks/java/library/j-jdbcnew/
Statement stmt = conn.createStatement();
// Obtain the generated key that results from the query.
stmt.executeUpdate("INSERT INTO authors " +
"(first_name, last_name) " +
"VALUES ('George', 'Orwell')",
Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
if ( rs.next() ) {
// Retrieve the auto generated key(s).
int key = rs.getInt(1);
}
Since PostgreSQL JDBC driver version 8.4-701 the PreparedStatement#getGeneratedKeys() is finally fully functional. We use it here almost one year in production to our full satisfaction.
In "plain JDBC" the PreparedStatement needs to be created as follows to make it to return the keys:
statement = connection.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);
You can download the current JDBC driver version here (which is at the moment still 8.4-701).
The sequences in postgresql are transaction safe. So you can use the
currval(sequence)
Quote:
currval
Return the value most recently obtained by nextval for this sequence
in the current session. (An error is
reported if nextval has never been
called for this sequence in this
session.) Notice that because this is
returning a session-local value, it
gives a predictable answer even if
other sessions are executing nextval
meanwhile.
Here is how I solved it, based on the answers here:
Connection conn = ConnectToDB(); //ConnectToDB establishes a connection to the database.
String sql = "INSERT INTO \"TableName\"" +
"(\"Column1\", \"Column2\",\"Column3\",\"Column4\")" +
"VALUES ('value1',value2, 'value3', 'value4') RETURNING
\"TableName\".\"TableId\"";
PreparedStatement prpState = conn.prepareStatement(sql);
ResultSet rs = prpState.executeQuery();
if(rs.next()){
System.out.println(rs.getInt(1));
}
If you are using Statement, go for the following
//MY_NUMBER is the column name in the database
String generatedColumns[] = {"MY_NUMBER"};
Statement stmt = conn.createStatement();
//String sql holds the insert query
stmt.executeUpdate(sql, generatedColumns);
ResultSet rs = stmt.getGeneratedKeys();
// The generated id
if(rs.next())
long key = rs.getLong(1);
If you are using PreparedStatement, go for the following
String generatedColumns[] = {"MY_NUMBER"};
PreparedStatement pstmt = conn.prepareStatement(sql,generatedColumns);
pstmt.setString(1, "qwerty");
pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
if(rs.next())
long key = rs.getLong(1);
Use sequences in postgres for id columns:
INSERT mytable(myid) VALUES (nextval('MySequence'));
SELECT currval('MySequence');
currval will return the current value of the sequence in the same session.
(In MS SQL, you would use ##identity or SCOPE_IDENTITY())
PreparedStatement stmt = getConnection(PROJECTDB + 2)
.prepareStatement("INSERT INTO fonts (font_size) VALUES(?) RETURNING fonts.*");
stmt.setString(1, "986");
ResultSet res = stmt.executeQuery();
while (res.next()) {
System.out.println("Generated key: " + res.getLong(1));
System.out.println("Generated key: " + res.getInt(2));
System.out.println("Generated key: " + res.getInt(3));
}
stmt.close();
Don't use SELECT currval('MySequence') - the value gets incremented on inserts that fail.
For MyBatis 3.0.4 with Annotations and Postgresql driver 9.0-801.jdbc4 you define an interface method in your Mapper like
public interface ObjectiveMapper {
#Select("insert into objectives" +
" (code,title,description) values" +
" (#{code}, #{title}, #{description}) returning id")
int insert(Objective anObjective);
Note that #Select is used instead of #Insert.
for example:
Connection conn = null;
PreparedStatement sth = null;
ResultSet rs =null;
try {
conn = delegate.getConnection();
sth = conn.prepareStatement(INSERT_SQL);
sth.setString(1, pais.getNombre());
sth.executeUpdate();
rs=sth.getGeneratedKeys();
if(rs.next()){
Integer id = (Integer) rs.getInt(1);
pais.setId(id);
}
}
with ,Statement.RETURN_GENERATED_KEYS);" no found.
Use that simple code:
// Do your insert code
myDataBase.execSQL("INSERT INTO TABLE_NAME (FIELD_NAME1,FIELD_NAME2,...)VALUES (VALUE1,VALUE2,...)");
// Use the sqlite function "last_insert_rowid"
Cursor last_id_inserted = yourBD.rawQuery("SELECT last_insert_rowid()", null);
// Retrieve data from cursor.
last_id_inserted.moveToFirst(); // Don't forget that!
ultimo_id = last_id_inserted.getLong(0); // For Java, the result is returned on Long type (64)
If you are in a transaction you can use SELECT lastval() after an insert to get the last generated id.