Retrieve two values from the same row using a single select statement - java

Why can't I retrieve two values from different fields but same row?
If I write this, it works perfectly.
String sql = "SELECT * FROM soal ORDER BY RAND() LIMIT 1";
ResultSet rs = st.executeQuery(sql);
String question = rs.getString("questions");
But after I add this
String hint = rs.getString("hint_questions");
It won't work.
NOTE: I need two Strings, question, and hint from the same row and class for different purpose. So I have to use single select query SQL so that value from question and hint is related (from the same row).

You can try Either of the solution:
String var = rs.getString(1);
through index
Or
String var = rs.getString("column_name");
through column name

Related

Java SQL Prepared Statement Issue with Array and Where... IN List [duplicate]

This question already has answers here:
How to use an arraylist as a prepared statement parameter [duplicate]
(4 answers)
Closed 3 years ago.
I have an Array List which contains Strings:
ArrayList<String> anrs = new ArrayList<>();
Now I convet those into an SQL array like this:
final String[] data = anrs.toArray(new String[anrs.size()]);
final java.sql.Array sqlArray = connection.createArrayOf("varchar", data);
And now I want to make a prepared statement like this:
statement = connection.createStatement();
String selectSQL = "SELECT * FROM rekopf INNER JOIN repos ON rekopf.rekopfnum=repos.Reposnum WHERE repos.reposart IN ?";
pstatement = connection.prepareStatement(selectSQL);
pstatement.setArray(1, sqlArray);
resultSet = pstatement.executeQuery();
But I got this error:
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.1 unexpected
token: ? required:
error occures in this line: pstatement = connection.prepareStatement(selectSQL);
What is my issue in this case? Thanks in advance.
Update When I try it like this:
pstatement.setArray(1, connection.createArrayOf("varchar", data));
Then I got this error
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.1
incompatible data type in conversion
java.sql.Array doesn't equate to java Arrays of any datatype. Some DBs have in-build support of Collections and Records types (e.g. Varray in Oracle). java.sql.Array comes handy to send data for such datatypes (mostly parameters to Procedures PL/SQLs) from client side. For any further information you may want to do some reading on Collections, Records and Types support for your database of choice.
For your need, you would simply want to write an SQL where each element from List becomes part of the IN clause
for example: select * from user where name in ('Hans', 'Joe', 'Jane');
//Your below code snippet,
ArrayList<String> anrs = new ArrayList<>();
// may be generated elsewhere as
// List<String> anrs = Arrays.asList("Hans", "Joe", "Jane");
// can be flattened to comma separated, quoted String
String inClause = anrs.stream().map(s -> "'"+s+"'")
.collect(Collectors.joining(","));
System.out.println("List<String> flattened for IN Clause -> "+inClause);
// which you will use to create SQL
String selectSQL = String.format("SELECT * FROM rekopf INNER JOIN repos "
+ "ON rekopf.rekopfnum=repos.Reposnum WHERE repos.reposart IN (%s)",
inClause);
java.sql.PreparedStatement pstatement =
connection.prepareStatement(selectSQL);
java.sql.ResultSet resultSet = pstatement.executeQuery();
while(resultSet.next()){
//TODO - process the result
}
Binding parameters to PreparedStatement for an SQL with In Clause is not straight forward. I leave this as an exercise for you, in case you want to go above and beyond.
The problem might be using ? as a placeholder.
Try ...WHERE repos.reposart IN (?)
As found here
Yes like the others said the ? is the issue.
In this case I do it like this:
String selectSQL = "SELECT * FROM rekopf INNER JOIN repos ON rekopf.rekopfnum=repos.Reposnum WHERE repos.reposart IN (";
int count = 0;
for (String anr : anrs){
selectSQL += "'"+anr+"'";
count++;
if (count < anrs.size()){
selectSQL += ",";
}
}
selectSQL += ")";
Thats not nice. But super efficient in this case.
Thanks.

PreparedStatement with hextoraw in hsqldb throws java.sql.SQLDataException: data exception: string data, right truncation

I'm transferring data from one hsqldb to another. Both have the same tables etc. The schemas are absolutely identical.
I have some massive binary columns (not my design decision, but I got to work with it). Those I read as a string with the rawtohex function from database A and write to database B using the hextoraw function.
The code looks something like that:
String query = "SELECT rawtohex(PAYLOAD) FROM TABLE_X;"
Statement selectPst = connA.createStatement();
ResultSet data = selectPst.executeQuery(query);
String insert = "INSERT INTO TABLE_X (PAYLOAD) VALUES (hextoraw(?))";
PreparedStatement insStmt = connB.prepareStatement(insert);
data.next();
insStmt.setString(1, data.getString(1));
insStmt.executeUpdate(); // <- java.sql.SQLDataException: data exception: string data, right truncation
Usually, this Exception is thrown if the column is too small for the data. But the data is in a database with the same table and columns and if I do the same thing manually using the hsqldb tool, it works.
I'm grateful for any idea what could possibly cause this!
Can you try with readBinaryStream and writeBinaryStream methods instead of using rawtohex, e.g.:
String query = "SELECT PAYLOAD FROM TABLE_X;"
Statement selectPst = connA.createStatement();
ResultSet data = selectPst.executeQuery(query);
String insert = "INSERT INTO TABLE_X (PAYLOAD) VALUES (?)";
PreparedStatement insStmt = connB.prepareStatement(insert);
data.next();
insStmt.setBinaryStream(1, data.getBinaryStream(1));
insStmt.executeUpdate();
It is not necessary to use RAWTOHEX and HEXTORAW.
String query = "SELECT PAYLOAD FROM TABLE_X;"
Statement selectPst = connA.createStatement();
ResultSet data = selectPst.executeQuery(query);
String insert = "INSERT INTO TABLE_X (PAYLOAD) VALUES (?)";
PreparedStatement insStmt = connB.prepareStatement(insert);
data.next();
byte[] databytes = data.getBytes(1);
// add code here to check if (databytes.length > columnSize)
insStmt.setBytes(1, databytes);
insStmt.executeUpdate(); //
It is possible in some scenarios that the data was inserted into the connA database without the size checks being applied. Adding some size checking code above will show you if this has happened and will allow you to alter the column size in both databases.

Display duplicate entries in SQL table using Java

I am currently trying to access the primary key by searching for a duplicate field in a database in java using sql statements. My database contains a primary key for the book ids and contains multiple copies of the same book. Those books have the same ISBN but different book ids. Is it possible to extract those unique ids using an SQL select statement? Whenever I run the following select statement, I can only obtain data on one of the copies:
String queryString =
"select bid, title, author, checked from book where isbn = " + ID;
ResultSet resultSet = stmt.executeQuery(queryString);
if (resultSet.next()){
bid = resultSet.getString(1);
title = resultSet.getString(2);
author = resultSet.getString(3);
checked = resultSet.getString(4);
}
resultSet.close();
If I run the same statement in my SQL workbench, all of the data is extracted. How can I extract the unique keys in java?
rset2.next() moves the cursor to the next row. Since you don't seem to have any loop iterating through the resultset, it isn't going beyond the first row.
You have used if condition that allows you to get only the first record fetched from query.
Rather use :
while(rs.next()) {
// TO DO
}
Change the if(resultSet.next()) for while(resultSet.next()) :
String queryString =
"select bid, title, author, checked from book where isbn = " + ID;
ResultSet resultSet = stmt.executeQuery(queryString);
// "while" instead of "if"
while (resultSet.next()){
bid = resultSet.getString(1);
// etc
// do something
}
resultSet.close();
"if" only get the first element, "while" get all the element
See the answer of this question: Similar Question

Get the number of rows from ResultSet

I am trying to get the number in ResultSet that I am getting from my query as in the code below. The query retrieves the number 5. How can I get this number from ResultSet?
Code:
String sql_count_stop = "select count(*) FROM behaviour where mac = ? ";
PreparedStatement preparedCount = con.prepareStatement(sql_count_stop);
preparedCount.setString(1, macD);
ResultSet rsCount = preparedCount.executeQuery();
while(rsCount.next()){
}
You can modify your query to
"SELECT count(*) AS totalCount FROM behaviour WHERE mac = ? ";
and then use,
macId= rsCount.getInt("totalCount");
Or use position rsCount.getInt(1) and you don't need a column alias.
Also since there will be only one row, if(rsCount.next()) is just as good as while, and in my opinion more clearly shows this logic will only execute once.
You can modify you SQL statement to: (added AS 'countMacs')
select count(*) as 'countMacs' FROM behaviour where mac = ?
Then get a value
while(rsCount.next()){
int count = rsCount.getInt("countMacs");
}

How do I save a resultset into a variable?

Good day, I have searched through a couple of questions in how to save the values in the resultset in a variable. Since I am using a function, I do not know what to put in the ResultSetVar.getString("") function.
Here is my query.
sqlSelectRecord1 = "SELECT COUNT(name) as acount from maintable where VLdate = ?";
psSelectRecord1=conn.prepareStatement(sqlSelectRecord1);
psSelectRecord1.setString(1, strDateofVL);
rsSelectRecord1=psSelectRecord1.executeQuery();
String strCount;
Integer iCount;
while (rsSelectRecord1.next()) {
strCount = rsSelectRecord1.getString(acount);
iCount = Integer.valueOf(strCount);
}
I am having an error that says acount cannot be resolved into a variable. I'm guessing it does not read my AS acount in my query. How do I make my way through this?
You must use a name.
strCount = rsSelectRecord1.getString("acount");

Categories

Resources