How to get current row inserted - java

I have a table, and in it I have
UsernameID,UniqueID, component, coorX, coorY, coorX2, coorY2.
The UniqueID is created by Auto Increment. I want to get the current row after I insert into my table. How do I insert the current row in MySQL? I'm using Java.
In php they used
mysql_insert_id()
Can you give me an example of a script to insert the current row in MySQL using Java?

It's JDBC standard feature, see Statement.executeUpdate(String sql, int autoGeneratedKeys), example:
Statement stmt = conn.createStatement();
stmt.executeUpdate("insert into t1 (UsernameID) values (1)", Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
long id = rs.getLong(1);

You can also use PreparedStatement for the same.
String ColumnsArray[] = {"columnName"};
String sqlQuery = " " // write your insert query here
PreparedStatement pstmt = conn.prepareStatement(sql,ColumnsArray);
pstmt.setString(1, "anyvalue");
pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
if(rs.next())
long key = rs.getLong(1);

Related

execute query in java not return results but in mysql workbench still return results

This query:
SELECT
r.report_id,
r.user_id,
u.user_name,
u.user_mail,
d.department_name,
r.report_comment,
r.report_target_date,
r.report_create_date,
r.report_revised_date,
r.report_root_id,
report_revised_id
FROM
report r
JOIN
user u ON u.user_id = r.user_id
JOIN
department d ON u.department_id = d.department_id
JOIN
authority a ON r.user_id = a.user_src_id
AND a.user_dest_id = 131
WHERE
r.report_target_date BETWEEN '2014-07-23 23:59:00' AND '2014-08-22 00:00:00'
AND r.report_comment LIKE '%事務%'
In mysql workbench this query has return value but when using it in java it's not returning anything:
Statement stmt = connection.createStatement();
ResultSet rs = null;
rs = stmt.executeQuery(query);
In mysql workbench this query has return value but rs return is empty.
You pass Japanese characters into the query. This could easily be a character encoding issue.
Use a PreparedStatement and insert the value through a setString() call which will properly take care of the encoding.
Modify your query to have a parameter (marked by a question mark):
...
WHERE
r.report_target_date BETWEEN '2014-07-23 23:59:00' AND '2014-08-22 00:00:00'
AND r.report_comment LIKE ?
And the Java code:
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, "%事務%"); // Parameter index is 1-based
ResultSet rs = ps.executeQuery();

How to resolve the id from MySQL DB into a variable

Is is possible to get the id from a MySQL table and "save" it into a variable on JDBC?
In my program, I have a JTextfield in which the user gives a ticket which will be stored on a MySQL DB. Everytime he gives a ticket, I want to get the id from my db where the ticket was inserted and not print in on teminal, but resolve it into a variable and use it on other classes also. I need it for other classes.
Is is possible?
Something like this ?
statement.executeUpdate();
ResultSet generatedKeys = statement.getGeneratedKeys();
long generatedId= 0L;
if (generatedKeys.next()) {
generatedId = generatedKeys.getLong(1);// here is your generated Id ,
}
Something like that?
PreparedStatement st;
st = con.prepareStatement("SQL STATAMENT", "HERE COLUMN NAME FROM TABLE") VALUES(?)",Statement.RETURN_GENERATED_KEYS);
st.setString(1,"Binded String Veriable");
st.executeUpdate();
ResultSet rs = st.executeQuery("select last_insert_id() as id from "HERE TABLE NAME"");
if(rs.next()){
int lastId = Integer.parseInt(rs.getString("id"));
Use PrpearedStatment to prevent SQL Injection for example:
st = con.prepareStatement("INSERT INTO component(user) VALUES(?)", Statement.RETURN_GENERATED_KEYS )
st.setString(1,username)
Here you have how last_insert_id() works: JDBC LAST INSER ID AND OTHER

Insert using PreparedStatement. How do I auto-increment the ID?

I have a PreparedStatement such as:
PreparedStatement preparedStatement = connect.prepareStatement("INSERT into employee (id, time, name" + "(?,?,?)",Statement.RETURN_GENERATED_KEYS);
ResultSet tableKeys = preparedStatement.getGeneratedKeys();
preparedStatement.executeUpdate();
tableKeys.next();
int autoGeneratedID = tableKeys.getInt(1);
preparedStatement.setInt(1,autoGeneratedID);
preparedStatement.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()));
preparedStatement.setString(3, "Test");
preparedStatement.executeUpdate();
As you can see, the Employee table has an auto-incremented ID. I need to basically add it in automatically using preparedStatement as well. Can someone tell me where I am going wrong and correct me? Right now it just gives me an error related to Statement.
Leave the column out of the INSERT statement entirely. It will be generated by the database engine. Your query should be:
INSERT INTO employee (time, name)
VALUES (?, ?)
Secondly, you have to perform the insert first, then get the keys out of the result.
I believe your code should be:
PreparedStatement preparedStatement =
connect.prepareStatement("INSERT into employee (time, name) VALUES (?,?)",
Statement.RETURN_GENERATED_KEYS);
preparedStatement.setTimestamp(1,
new java.sql.Timestamp(new java.util.Date().getTime()));
preparedStatement.setString(2, "Test");
preparedStatement.executeUpdate();
ResultSet tableKeys = preparedStatement.getGeneratedKeys();
tableKeys.next();
int autoGeneratedID = tableKeys.getInt(1);
Note this example does not check the success of the executed statement or the existence of returned keys.
You should perform some modification(define default statement) to prepared statement string like this:
"INSERT into employee VALUES(default,?,?)"
That modification is because of occurring this problem : Column count doesn't match value count at row 1 JAVA mysql
After that you're code is something like below:
PreparedStatement preparedStatement =
connect.prepareStatement("INSERT into employee VALUES (default,?,?)", Statement.RETURN_GENERATED_KEYS);
preparedStatement.setTimestamp(1, new java.sql.Timestamp(new java.util.Date().getTime()));
preparedStatement.setString(2, "Test");
preparedStatement.executeUpdate();
ResultSet tableKeys = preparedStatement.getGeneratedKeys();
tableKeys.next();
Thanks to Ic. for his answer.
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","password");
PreparedStatement ps = con.prepareStatement("insert into imgslider(id,cmnt,date1,img,status) values(seq.nextval,?,?,?,?)");
ResultSet rs = null;
String s1 = "I’ve Come and I’m Gone: A Tribute to Istanbul’s Street";
ps.setString(1,s1);
Calendar calendar = Calendar.getInstance();
java.sql.Date dd = new java.sql.Date(calendar.getTime().getTime());
ps.setDate(2,dd);
FileInputStream f1 = new FileInputStream("F:\\java\\slide-9.jpg");
ps.setBinaryStream(3,f1,f1.available());
ps.setInt(4,0);
int i = ps.executeUpdate();
System.out.println(i+" rows affected");
con.close();
}
here is my code for auto-increment column in table by PreparedStatement.

How to check if a record with a specific primary key exists in a MySql table from JDBC

How can i find out, from a Java program using JDBC if my table has a record with a specific primary key value? Can i use the ResultSet somehow after i issue a SELECT statement?
Count might be a better idea for this case. You can use it like so:
public static int countRows(Connection conn, String tableName) throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName + " WHERE.... ");
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
} finally {
rs.close();
stmt.close();
}
return rowCount;
}
Taken from here.
You can do something like
private boolean hasRecord(String id) throws SQLException {
String sql = "Select 1 from MyTable where id = ?";
PreparedStatement ps = dbConn.prepareStatement(sql);
ps.setString(1,id);
ResultSet rs = ps.executeQuery();
return rs.next();
}
You can do that in four steps.
Write SQL. Something like select count(1) from table where column = 34343 will do.
Learn how to get connection using JDBC.
Learn about PreparedStatements in Java.
Learn how to read values from ResultSet.
select case
when exists (select 1
from table
where column_ = '<value>' and rownum=1)
then 'Y'
else 'N'
end as rec_exists
from dual;

Is there a way to retrieve the autoincrement ID from a prepared statement

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);
}

Categories