Inserting auto generated id in sqllite using java [duplicate] - java

This question already has an answer here:
How to perform an SQL insert in Java
(1 answer)
Closed 7 years ago.
I am writing java application using sqllite
public Product createProduct(String productName) throws SQLException {
String query = "INSERT into tbl_Product (name) values (?) ";
PreparedStatement preparedStatement = null;
Connection connection = null;
ResultSet rs = null;
Product product = null;
try {
connection = ConnectionFactory.getConnection();
preparedStatement = connection.prepareStatement(query);
//preStatement.setInt(1, 0);
preparedStatement.setString(1, productName);
preparedStatement.executeUpdate();
} finally {
//preparedStatement.close();
DbUtil.close(rs);
DbUtil.close(preparedStatement);
DbUtil.close(connection);
}
return product;
}
My product table have (ID,Name) column, where Id is auto generated. What all java changes are required so that preStatement can insert auto generated id in db.

String query = "INSERT into tbl_Product values (?) ";
ResultSet rs = null;
Product product = null;
try {
connection = ConnectionFactory.getConnection();
preStatement = (PreparedStatement) connection.prepareStatement(query);
preStatement.setString(1, productName);
rs = preStatement.executeQuery();

String sqlQuery = "INSERT into tbl_Product values (?)
PreparedStatement stmt = conn.prepareStatement(sqlQuery);
stmt.setString( 1, "val" ); //nameText variable contains the text of the jtextfield)
stmt.executeUpdate();
use execute update instead of execute query.
executeQuery():
Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.
executeUpdate():
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.

Related

how to pass the id value using name from one table to another table and store the information to database [duplicate]

This question already has answers here:
java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) [closed]
(2 answers)
Closed 4 years ago.
Sql query how to pass the id from department table using the department name to the user table using the department id
here in department table dept_id is primary key
and dept_id in user table is foreign key
how to select the dept_id using department_name from the department table and store the value in the user table
try{
Connection con = DBconnect.getConnection();
//selecting the dpartment
String sql ="select DEPARTMENT_CODE,DEPARTMENT_NAME from department_info";
PreparedStatement ps = con.prepareStatement(sql);
String s11=comboboxdeptid.getItems().toString();
ResultSet rs=ps.executeQuery();
if(rs.next()==true)
{
if(rs.getString("DEPARTMENT_NAME").equals(comboboxdeptid.getSelectionModel().toString()))
rs.getString("DEPARTMENT_CODE");
}
//second stmt
String sql1 = "insert into user_info(USER_NAME, FIRST_NAME, LAST_NAME, DESIGNATION, ADDRESS,PASSWORD_TXT,DEPARTMENT_CODE,CREATED_BY) values(?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql1);
String s12 = nameid.getText();
String s13 = Firstnameid.getText();
String s14 = Lnameid.getText();
String s15 = desigid.getText();
String s16 = comboboxdeptid.getItems().toString();
String s17 = addrsid.getText();
String s18 = passwordid.getText();
ps.setString(1, s12);
ps.setString(2, s13);
ps.setString(3, s14);
ps.setString(4, s15);
ps.setString(5, s17);
ps.setString(6, s18);
ps.setString(7, s11);
ps.setString(8, "abc");
ps.execute();
ResultSet rs1=ps1.executeQuery();
//third stmt
String sql2 = "update security_qa_info set SECURITY_QUESTION=?, SECURITY_ANSWER=? where USER_ID=?";
PreparedStatement ps2 = con.prepareStatement(sql2);
String s19 = securityquestionid.getSelectionModel().getSelectedItem().toString();
String s20 = answerid.getText();
while(rs2.next()==true)
{
if(rs2.getString("USER_NAME").equals(nameid.getText()))
{
rs2.getString("USER_ID");
ps2.setString(1, s16);
}
}
ps2.setString(2, s19);
ps2.setString(3, s20);
ps2.executeUpdate();
showMessageDialog(null, "Registration Successful");
}catch(Exception e){
// showMessageDialog(null, e);
e.printStackTrace();
}
Parent fxml = FXMLLoader.load(getClass().getResource("/com/abc/fxml/LoginPage.fxml"));
pane2.getChildren().setAll(fxml);
} else {
showMessageDialog(null, "Passwords don't match!");
}
}
ps = prepared statement for SELECT query:
String sql ="select DEPARTMENT_CODE,DEPARTMENT_NAME from department_info";
PreparedStatement ps = con.prepareStatement(sql);
ps1 = prepared statement for INSERT statement:
String sql1 = "insert into user_info(USER_NAME, FIRST_NAME, LAST_NAME, DESIGNATION, ADDRESS,PASSWORD_TXT,DEPARTMENT_CODE,CREATED_BY) values(?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql1);
Using the wrong prepared statement:
ps.setString(1, s12);
A suggestion - if you call the first prepared statement 'selectDepartmentDetails' and the second 'insertUserInfo', it is less likely you will run into this.

PreparedStatement issue in postgresql (select query) [duplicate]

I have a typical crosstab query with static parameters. It works fine with createStatement. I want to use preparestatement to query instead.
String query = "SELECT * FROM crosstab(
'SELECT rowid, a_name, value
FROM test WHERE a_name = ''att2''
OR a_name = ''att3''
ORDER BY 1,2'
) AS ct(row_name text, category_1 text, category_2 text, category_3 text);";
PreparedStatement stat = conn.prepareStatement(query);
ResultSet rs = stat.getResultSet();
stat.executeQuery(query);
rs = stat.getResultSet();
while (rs.next()) {
//TODO
}
But it does not seem to work.
I get a PSQLException -
Can't use query methods that take a query string on a PreparedStatement.
Any ideas what I am missing?
You have fallen for the confusing type hierarchy of PreparedStatement extends Statement:
PreparedStatement has the same execute*(String) methods like Statement, but they're not supposed to be used, just use the parameterless execute*() methods of PreparedStatement --- you already have given the actual query string to execute using conn.prepareStatement().
Please try:
String query = "...";
PreparedStatement stat = conn.prepareStatement(query);
ResultSet rs = stat.executeQuery();
while (rs.next()) {
// TODO
}

Return id after sql insert java [duplicate]

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 retrieve values from SQL when ID is in array form

The function below will pick the highest value and it will display value which are in column place1(in table placeseen) as output based on the ID.So far I only can get the highest value but not the value in place1.
I don't know what's wrong with my coding because the output is always shows empty.
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=aa[0+1];
for(int i=0;i<aa.length;i++)
{
if(aa[i]>highest){
highest=aa[i];
String sql ="Select* from placeseen where ID =aa[i]";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
ps.close();
rs.close();
conn.close();
}
}
System.out.println(highest);
}
instead of
String sql ="Select * from placeseen where ID =aa[i]";//aa[i] taking a value
use
String sql ="Select place1 from placeseen where ID =?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]);
passing aa[i] variable value .
Avoid sql injection
You can try this
// as you are using preparedStatement you can use ? and then set value for it to prevent sql injection
String sql = "Select * from placeseen where ID = ?";
DatabaseConnection db = new DatabaseConnection();
Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]); // 1 represent first attribute represented by ?
System.out.println(ps); // this will print query in console
ResultSet rs = ps.executeQuery();
if (rs.next()) {
System.out.println("Inside rs.next()"); // for debug purpose
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
// remaining code

How to use java variable to insert values to mysql table?

Hi i am trying to insert the values in to mysql table. i am trying this code.
i have assigned values to variable and i want to pass that variable to that insert statement.
Is this correct?
code
int tspent = "1";
String pid = "trng";
String tid = "2.3.4";
String rid = "tup";
String des = " polish my shoes!";
INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');
here is what i have tried, but i am not able to insert values
try
{
conn=DBMgr.openConnection();
String sqlQuery = "INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');";
st = conn.createStatement();
rs = st.executeQuery(sqlQuery);
}
You should use executeUpdate() method whenever your query is an SQL Data Manipulation Language statement. Also, your current query is vulnerable to SQL Injection.
You should use PreparedStatement:
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUES (?, ?, ?, ?, ?)");\
Then set the variables at those index:
pstmt.setString(1, pid);
// Similarly for the remaining 4
// And then do an executeUpdate
pstmt.executeUpdate();
Try this,
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String uname="username";
String pass="password";
Class.forName(driver);
Connection c=(Connection) DriverManager.getConnection(url,uname,pass);
Statement s=c.createStatement();
s.executeUpdate("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"')");
Use a PreparedStatement and set the values using its setXXX() methods.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO `time_entry`
(pid,tid,rid,tspend,description) VALUE
(?,?,?,?,?)");
pstmt.setString(1, pid );
pstmt.setString(2, tid);
pstmt.setString(3, rid);
pstmt.setInt(4, tspent);
pstmt.setString(5,des );
pstmt.executeUpdate();
import java.sql.*;
class Adbs1{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/rk","root","#dmin");
//here rk is database name, root is username and password
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into emp values('rk11','Irfan')");
// stmt.executeUpdate("delete from emp where eid ='rk4'");
//stmt.executeUpdate("update emp set ename='sallu bhai' where eid='rk5'");
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

Categories

Resources