How to resolve the id from MySQL DB into a variable - java

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

Related

Can not get inserted primary key at JDBC

I am working with Microsoft SQL Server in my project and I am using JDBC as connector. My project runs within Tomcat Server. What I am trying to do is gettiing primary key of a newly inserted value without writing one more select statement.
Here is my java code:
PreparedStatement ps = conn.prepareStatement("INSERT INTO Users(FIRSTNAME,STATUS)VALUES " +
"(?,?)", Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "name");
ps.setInt(2, status);
int updatedRows = ps.executeUpdate();
if(updatedRows > 0){
ResultSet resultSet = ps.getGeneratedKeys();
if (resultSet.next()) {
// do some stuff with resultSet.getInt(1)
// but code does not enter here
}
}
But code does not enter the inner if clause statement as I mentioned in my comment. I also tried this:
PreparedStatement ps = conn.prepareStatement("INSERT INTO Users(FIRSTNAME,STATUS)VALUES " +
"(?,?)", new String[]{"USERID"});
Here USERID is name of the primary key of Users table. Both method did not worked. How can I solve this?
try this:
INSERT INTO Users(FIRSTNAME,STATUS) OUTPUT Inserted.ID VALUES (?,?)

How to read sqlite text column using jdbc prepared statement in java?

Here is my sqlite table
CREATE TABLE hello (
id INTEGER PRIMARY KEY AUTOINCREMENT,
import_data text,
export_data text
);
Here is my java code
Connection sqliteConnection = DriverManager.getConnection(db);
PreparedStatement preparedStatement = sqliteConnection.prepareStatement("select * from hello where export_data = ?;");
preparedStatement.setString(1, "ABD19E3C63"); // hex string
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
importData = resultSet.getString("import_data");
System.out.println(importData); // prints nothing although I checked in the sqlite database that it exists.
so importData prints nothing although I can see in the sqlite database that it exists. not sure why?
sqlite query
select hex(import_data) from hello where hex(export_data)="ABD19E3C63"; // This works
The above query works in sqlite although I declared both columns as text
Should you try this?
PreparedStatement preparedStatement = sqliteConnection.prepareStatement("select * from hello where hex(export_data) = ?;");
You should use looping statement like the following.
while (resultSet.next()) {
String import_data= resultSet.getString("import_data");
System.out.println("Import_data"+import_data);
}

How to get current row inserted

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

Ms access "invalid record set status" error

I connect to my access database successfully and my sql is works and after these i have a result set. Code is below:
Statement stmt = con.createStatement();
String sqlStr ="select max(ID) from GuestBook ";
ResultSet rset = stmt.executeQuery(sqlStr);
But when i want to get value from resultset like this;
int id = rset.getInt(1);
or
int id = rset.getInt("ID");//or "max(ID)"
I have a sql exception.
Exception is "invalid record set status"
How can i solve this problem?
A column name of "Expr1000" will be generated for max(ID). But I think that it is better to use an As clause to give it a well defined alias.
You must call rset.next() in order to move to the first row, because initially, the cursor is positioned before the first row.
Statement stmt = con.createStatement();
String sqlStr ="SELECT max(ID) As LastID FROM GuestBook";
ResultSet rset = stmt.executeQuery(sqlStr);
int id = 0;
if (rset.next()) {
id = rset.getInt("LastID");
// OR
id = rset.getInt(1);
}

Getting null value in the foreign key field of my table in Mysql

I have 2 tables in my application:
1.newuser
2.introducer_table
Newuser1 table contains *sid**(primary key,auto-generated field)****, fathername,gender,datebirth,occupation,addharnumber as columns
1.I’m inserting values into the newuser table using java prepared statement like below:
PreparedStatement pst = con.prepareStatement("insert into newuser1 (name,fathername,gender,datebirth,occupation,aadharNumber) values(?,?,?,?,?,?)");
//pst.setString(1,NULL);
pst.setString(1,”xyz”);
pst.setString(2,"ram");
pst.setString(3,"male");
pst.setString(4,"oct25");
pst.setString(5,"emps");
pst.setString(6,"4564");
data is inserted successfully,but I want the sid value of newuser1 in my introducer_table so I write the query like this in prepared statement to select the last insert id.
My introducer_table contains the columns:
**sid(foreign key),name,accountno,sign**
PreparedStatement pst = con.prepareStatement("insert into introducer_table(sid,name,accountno,sign) values((SELECT LAST_INSERT_ID() from dual),?,?,?)");
//nomine details into data base
//pst.setString(1,NULL);
pst.setString(1,"ram");
pst.setString(2,"8945");
pst.setString(3,"ssss");
When I execute this,Im getting ‘0’ value in the sid column of introducer_table.I make sid column as not null while creating intoducer_table,even im getting the ‘zero’ value like this:
Introducer_table:
**Sid** name accountno sign
**0** ram 8945 ssss
Please help me I was stucked by this problem from so many days.
Rather than doing it your way think about using
con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
and then after your insert
pst.executeUpdate();
ResultSet rs = prest.getGeneratedKeys();
  
int last_inserted_id = -1;
if(rs.next())
{
last_inserted_id = rs.getInt(1);
}

Categories