get last inserted row id in ebean with sqlupdate - sql

If I am using ebean sqlupdate to do insert into Oracle in Java
Transaction tx = Ebean.beginTransaction();
try {
Transaction tx = Ebean.beginTransaction();
try {
String sqlString = "INSERT INTO customers VALUES (1001,'Nichols', 'Alexandra', '17 Maple Drive', "+ "'Nashua', 'NH','03062', SDO_GEOMETRY(2001, 8307, SDO_POINT_TYPE (-71.48923,42.72347,NULL), NULL, NULL))";
SqlUpdate query = Ebean.createSqlUpdate(sqlString);
query.execute();
String sqlQuery =
"SELECT ##IDENTITY AS 'Identity'";
SqlQuery query2 = Ebean.createSqlQuery(sqlQuery);
List<SqlRow> list = query2.findList();
System.out.println(list.get(0));
} finally {
tx.commit();
}
It gives error
[PersistenceException: Query threw SQLException:ORA-00936: missing expression
Query was:
SELECT ##IDENTITY AS 'Identity'
]
How do I get the id of last inserted row?

After an INSERT, SELECT INTO, or bulk copy statement is completed, ##IDENTITY contains the last identity value that is generated by the statement.
But this is in sql So i think you should create the USP and you can return the last inserted record id as outparm from the USP
String sqlString = "INSERT INTO customers VALUES (1001,'Nichols', 'Alexandra', '17 Maple Drive', "+ "'Nashua', 'NH','03062', SDO_GEOMETRY(2001, 8307, SDO_POINT_TYPE (-71.48923,42.72347,NULL), NULL, NULL))";
SqlUpdate query = Ebean.createSqlUpdate(sqlString);
query.execute();
SELECT ##IDENTITY AS 'Identity';

Related

Insert data into 2 related tables at once?

I am trying to insert into two tables at once using the primary key from the first table to insert into the second but I am not sure how to go about it.
My table structure is as follows:
Person
PersonId
FirstName
Surname
Employee
EmployeeId
HoursWorked
PersonId in the Person table is an auto incremented column. EmployeeId in the second table is a primary and foreign key that should be the same as PersonId.
I been trying with this query string which I found on Google but with not much luck:
string queryString = "BEGIN TRANSACTION DECLARE #DataID int; "
+"INSERT INTO Person(FirstName, Surname) VALUES(#firstName, #surname);"
+ "SELECT #DataID = scope_identity();"
+ "INSERT INTO Employee VALUES(#DataId, #hoursWorked);"
+ "COMMIT";
From C#, you can try something like this:
// define the INSERT query - insert a firstname,surname into "Person",
// and insert a row into the Emplyoee table with the new ID
// created by the first insert
string insertStmt = #"BEGIN TRANSACTION
INSERT INTO dbo.Person(FirstName, Surname) VALUES(#FirstName, #Surname);
DECLARE #NewPersonId INT = SCOPE_IDENTITY();
INSERT INTO dbo.Employee(EmployeeId, HoursWorked) VALUES(#NewPersonId, #HoursWorked);
COMMIT TRANSACTION;"
// define connection and command for inserting data
using (SqlConnection conn = new SqlConnection(-your-connection-string-here-))
using (SqlCommand cmdInsert = new SqlCommand(insertStmt, conn))
{
// Define parameters - adapt datatype and max length as required
cmdInsert.Parameters.Add("#FirstName", SqlDbType.VarChar, 100);
cmdInsert.Parameters.Add("#Surname", SqlDbType.VarChar, 100);
cmdInsert.Parameters.Add("#HoursWorked", SqlDbType.Int);
// set parameter values
cmdInsert.Parameters["#FirstName"].Value = "John";
cmdInsert.Parameters["#Surname"].Value = "Doe";
cmdInsert.Parameters["#HoursWorked"].Value = 35;
// Open connection, execute query, close connection
conn.Open();
int rowsInserted = cmdInsert.ExecuteNonQuery();
conn.Close();
}
Update: as mentioned by #charlieface, you can write this code more concisely IF you're only ever inserting a single row - like this:
// define connection and command for inserting data
using (SqlConnection conn = new SqlConnection(-your-connection-string-here-))
using (SqlCommand cmdInsert = new SqlCommand(insertStmt, conn))
{
// Define and set parameters
cmdInsert.Parameters.Add("#FirstName", SqlDbType.VarChar, 100).Value = "John";
cmdInsert.Parameters.Add("#Surname", SqlDbType.VarChar, 100).Value = "Doe";
cmdInsert.Parameters.Add("#HoursWorked", SqlDbType.Int).Value = 35;
// Open connection, execute query, close connection
conn.Open();
int rowsInserted = cmdInsert.ExecuteNonQuery();
conn.Close();
}
You need to specify the columns you are inserting into.
You should also use SET XACT_ABORT ON if you have an explicit transaction.
Note also the use of a multi-line string.
string queryString = #"
SET XACT_ABORT ON;
BEGIN TRANSACTION;
INSERT INTO Person (FirstName, Surname)
VALUES(#firstName, #surname);
DECLARE #DataID int = scope_identity();
INSERT INTO Employee (EmployeeId, HoursWorked)
VALUES(#DataId, #hoursWorked);
COMMIT;
";

how to use ">" or "<" as variable in javafx sqlite query

I have created a combobox in javafx and I want to query the sqlite db for data which are greater or less than what is selected from the combobox.
Combobox have ObservableList "10,20,30,40,50"
My query is " Select * From table Where age ( xxx ) ?"
xxx can be (" >=" or "<=")
this is my query
String qry_age = "Select * From table Where age (>=) ?";
PreparedStatement ps_age = connect.prepareStatement(qry_age);
ps_age.setInt(1,15);
ResultSet rs_age = ps_age.executeQuery();
while (rs_age.next()) {
System.out.println(rs_age.getString("age"));
}
You could simply use string concatenation to construct the query:
String ageCompareOperator = ">="; // or something else e.g. value from ComboBox
String qry_age = "Select * From table Where age " + ageCompareOperator + " ?";
PreparedStatement ps_age = connect.prepareStatement(qry_age);
...

Number of query values and destination fields are not the same (Union)

Running into this SQL error - number of query values and destination fields are not the same (Union). Using an Access database. The programList table has just two fields in it - userID and programID. Using parameters in my cs file. Here is the complete method:
public void AddProgramList (string program, int userID)
{
dbConnection.Open();
string sqlStmt = "INSERT INTO programs (program) ";
sqlStmt += "VALUES (#program)";
string sqlStmt2 = "INSERT INTO programList (userID, programID) " +
"SELECT userID " +
"FROM users" +
"WHERE userID = #userID " +
"UNION " +
"SELECT programID " +
"FROM programs" +
"WHERE program = #program;";
OleDbCommand dbCommand = new OleDbCommand(sqlStmt, dbConnection);
OleDbParameter param = new OleDbParameter("#program", program);
dbCommand.Parameters.Add(param);
dbCommand.Parameters.Add(new OleDbParameter("#userID", userID));
OleDbCommand dbCommand2 = new OleDbCommand(sqlStmt2, dbConnection);
OleDbParameter param2 = new OleDbParameter("#program", program);
dbCommand2.Parameters.Add(param2);
dbCommand2.Parameters.Add(new OleDbParameter("#userID", userID));
dbCommand.ExecuteNonQuery();
dbCommand2.ExecuteNonQuery();
dbConnection.Close();
}
If you printed out the SQL, you would see:
INSERT INTO programList (userID, programID) " +
SELECT userID FROM usersWHERE userID = #userID UNION SELECT programID FROM programsWHERE program = #program;
The error should be pretty obvious. You probably don't have a table called usersWHERE.
As I look at the problem, you are trying to insert two columns. So, I think you intend:
INSERT INTO programList (userID, programID)
SELECT userID, programID
FROM users, programs
WHERE userID = #userID AND program = #program;
Or, more simply:
INSERT INTO programList (userID, programID)
SELECT #userID, programid
FROM programs
WHERE program = #program;

Passing hexadecimal hash value to JDBC query

I have a table in my MYSQL database with hexadecimal(md5 hash values), I pick the values in one Query1 iterate over the resultset RS1 and Now I need to Fetch data from another table which has this hash value in the key column..I get an sql syntax error for executing the same:
String targetQuery = "select hashValue from targettbl ";
String sourceQuery = "select st.* from sourcetbl st where seqNo in" +
"(select seqNo from sourcetblkey where hashValue in (?)" ;
try {
stmt1 = conn.createStatement();
stmt2 = conn.prepareStatement(sourceMD5Query);
rs1 = stmt1.executeQuery(targetMd5Query);
while(rs1.next())
{
stmt2.setString(1, rs1.getString(1));
rs2 = stmt2.executeQuery(sourceQuery);
ResultSetMetaData rsmd = rs2.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while(rs2.next())
{
System.out.println("Source Row");
for(int i=1;i<columnsNumber;i++)
{
System.out.println(""+rs2.getString(i));
}
}
}
Error:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
Pls help
There is a )missing at end of your statement. Change it to this:
String sourceQuery = "select st.* from sourcetbl st where seqNo in" +
"(select seqNo from sourcetblkey where hashValue in (?))" ;

Second ResultSet.next() reporting true but while loop existing

While using a JDBC connection I am trying to perform 2 SELECT statements. The first returns a single record from a table (SQL_IBGN), and the second is designed to return multiple records from another table (SQL_ITXN) using a column (BGNREF) from the first query.
I have separate Statement and ResultSet objects for each query.
Code for Query 1:
Statement stmt = con.createStatement();
String sql = "SELECT BGNREF..... FROM SQL_IBGN WHERE BGNREF LIKE '2306009';";
ResultSet rs = stmt.executeQuery(sql);
String bgnref = null;
while (rs.next()) {
G1SQL_IBGN g1rec = new G1SQL_IBGN();
bgnref = rs.getString(1);
g1rec.setBGNREF(bgnref);
}
Code for Query 2:
if (bgnref != null) {
Statement stmt1 = con.createStatement();
String sql1 = "SELECT ACT_DESC...... SQL_ITXN WHERE BGNREF LIKE '"
+ bgnref + "';"; // Execute the SELECT statement ResultSet
ResultSet rs1 = stmt1.executeQuery(sql1); // Get result of first five records
while (rs1.next()) {
G1SQL_ITXN g1itxn = new G1SQL_ITXN();
g1itxn.setACT_DESC(rs1.getString(1));
}
}
The first query is returning a single record, however even though rs1.next() = true, the second while loop, while (rs1.next()) is not executed.