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.
Related
Trying to pass column name as parameter but JPA sets it as a value surrounding it with single quotes.
#NamedNativeQueries({
#NamedNativeQuery(
name = "Genre.findAllLocalized",
query = "SELECT "
+ " CASE "
+ " WHEN ? IS NULL THEN genre_default"
+ " ELSE ? "
+ " END localized_genre "
+ "FROM genre ORDER BY localized_genre")
})
Then:
List<String> res = em.createNamedQuery("Genre.findAllLocalized")
.setParameter(1, colName)
.setParameter(2, colName)
.getResultList();
The problem is that the column names being passed are taken as values so the result will return result list with repeated values of "col_name" instead of selecting the value of the column passed as parameter.
Is this achievable?
Basically it makes no sense to create a prepared query like this, how would you name that query anyway: "*"? So the short answer is: no.
But you could create named queries dynamically if this matches your requirement:
String colName = "colName";
String query = "SELECT WHEN " + colName + " IS NULL THEN genre_default";
Query query = entitymanager.createQuery(query);
Probably using a criteria builder is more the way you want to use JPA (code from https://en.wikibooks.org/wiki/Java_Persistence/Criteria):
// Select the employees and the mailing addresses that have the same address.
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
Root employee = criteriaQuery.from(Employee.class);
Root address = criteriaQuery.from(MailingAddress.class);
criteriaQuery.multiselect(employee, address);
criteriaQuery.where( criteriaBuilder.equal(employee.get("address"), address.get("address"));
Query query = entityManager.createQuery(criteriaQuery);
List<Object[]> result = query.getResultList();
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);
...
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';
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 (?))" ;
I try to prevent SQL injection in SQL query. I used following code to do it but unfortunately I faced some problem. The query is not running in oracle DB:
strQuery = #"SELECT PASSWORD FROM IBK_USERS where upper(user_id) =upper(:UserPrefix) AND user_suffix=:UserSufix AND STATUS_CODE='1'";
//strQuery = #"SELECT PASSWORD FROM IBK_CO_USERS where user_id = '" + UserPrefix + "' AND user_suffix='" + UserSufix + "' AND STATUS_CODE='1'";
try
{
ocommand = new OracleCommand();
if (db.GetConnection().State == ConnectionState.Open)
{
ocommand.CommandText = strQuery;
ocommand.Connection = db.GetConnection();
ocommand.Parameters.Add(":UserSufix", OracleDbType.Varchar2,ParameterDirection.Input);
ocommand.Parameters[":UserSufix"].Value = UserSufix;
ocommand.Parameters.Add(":UserPrefix", OracleDbType.Varchar2,ParameterDirection.Input);
ocommand.Parameters[":UserPrefix"].Value = UserPrefix.ToUpper();
odatareader = ocommand.ExecuteReader();
odatareader.Read();
if (odatareader.HasRows)
{
Your parameters shouldn't contain the semicolon :. This is just an indicator in your query that the variable that follows is a parameter, but you don't have to supply that on the .NET side:
ocommand.Parameters["UserSufix"] = ...