How do I insert last_insert_id using preparedStatement? - java

I am facing difficulty in inserting " last_insert_id" in my prepared statement.I got how to select the last_insert_id in prepared statement like below:
PreparedStatement getLastInsertId = con.prepareStatement("SELECT LAST_INSERT_ID()");
When I use the same procedure for inserting last_insert_id in my preparedstatement like this:
1. PreparedStatement pst = con.prepareStatement("insert into introducer_table values(?,?,?,?)");
2.
3. //introducer details into database
4. pst.setString(1,LAST_INSERT_ID());
5. pst.setString(2, nameofintroducer);
6. pst.setString(3, accountno);
7. pst.setString(4, signofintroducer);
Im getting 'null' value in the first column.can any one help me to come out from this problem

If your doing both the save actions at a time use getGeneratedKeys(), It's pretty much java.
I'm not a SQL guru, but here I found a way to get the generated id using getGeneratedKeys()
long generatedId= 0L;
statement = con
.getConnection()
.prepareStatement(
"insert into new_user set name= ? , contact= ? , ....",
statement.RETURN_GENERATED_KEYS);
statement.setString(1, "examplename");
statement.setString(2, "examplecontact");
------
statement.executeUpdate();
ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
generatedId = generatedKeys.getLong(1);// here is your generated Id , use it to insert in your introducer_table
}
PreparedStatement pst = con.prepareStatement("insert into introducer_table values(?,?,?,?)");
//introducer details into database
pst.setString(1, generatedId);
pst.setString(2, nameofintroducer);
pst.setString(3, accountno);
pst.setString(4, signofintroducer);

Related

i want to sum a column of sql table where date is current date

i want to sum the values of a column where date is today's date and pass it to a variable. i wrote the following code but it's not working.
error: "column name sum(Bill_Total) not valid." its considering "sum(Bill_Total)" as a column.
String sql = "select sum(Bill_Total) from t_report where date=?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setDate(1, date);
ResultSet rs = pst.executeQuery();
String sum=rs.getString(sql);
can someone tell me whats wrong with my query. thanks in advance
Is it me or the error is when you're fetching the result?
String sql = "select sum(Bill_Total) as bill_total from t_report where date=?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setDate(1, date);
ResultSet rs = pst.executeQuery();
String sum=rs.getString("bill_total");
Try this:
SELECT SUM(Bill_Total) AS `Bill_Total`
FROM t_report
WHERE date=?

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

Exception in prepared statement

Following is the code.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:cse");
//Statement stmt;
ResultSet rset;
//stmt = conn.createStatement();
String sql = " Select * from registration where id=?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, "101");
rset = pst.executeQuery(sql);
while (rset.next()) {
arr.add(rset.getInt("id"));
arr.add(rset.getString("first"));
arr.add(rset.getString("last"));
arr.add(rset.getInt("age"));
}
System.out.println(arr);
pst.close();
conn.close();
For the above am getting "Error: java.sql.SQLException: Driver does not support this function". What might be the problem?
You are misusing the PreparedStatement interface. When using PreparedStatements, you should prepare the statement with your query, bind all necessary parameters and then execute it without any SQL - this will cause the statement to execute the previously prepared SQL statement:
String sql = "Select * from registration where id=?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, "101");
rset = pst.executeQuery(); // Note - No args in the executeQuery call

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.

Invalid column index , update using PreparedStatement

I am updating table using PreparedStatement
the following code works perfectly
pst = conn.prepareStatement("UPDATE playjdbc SET jlname ='javafx10new' WHERE jfname = 'java10'");
int i = pst.executeUpdate();
but when i tried like this it throwing exception
pst = conn.prepareStatement("UPDATE playjdbc SET jlname ='javafx10new' WHERE jfname =?");
pst.setString(2, "java10"); // yeah second column is jfname
int i = pst.executeUpdate();
stacktrace :
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.OraclePreparedStatement.setStringInternal(OraclePreparedStatement.java:5330)
at oracle.jdbc.driver.OraclePreparedStatement.setString(OraclePreparedStatement.java:5318)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.setString(OraclePreparedStatementWrapper.java:282)
at com.indus.database.EmployeeDTO.updateData(EmployeeDTO.java:114)
2 in following refers to the position of the question mark in query string, not to the position of column in database table and not to the order of column names used in query:
pst.setString(2, "java10"); // yeah second column is jfname
Use 1 instead.
pst.setString(1, "java10"); // first question mark is jfname
Please go through the setString() method specs:
http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/PreparedStatement.html#setString%28int,%20java.lang.String%29
The correct approach is :
pst = conn.prepareStatement("UPDATE playjdbc SET jlname ='javafx10new' WHERE jfname =?");
pst.setString(1, "java10");
int i = pst.executeUpdate();

Categories