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");
Related
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.
i guess i'm too tired or what.. Can't see anything bad here.
String select = "SELECT project_id FROM project WHERE project_key = ?";
PreparedStatement preparedStatement1 = con.prepareStatement(select);
preparedStatement1.setString(1, project_key);
ResultSet rs = preparedStatement1.executeQuery();
int project_id = 0;
while(rs.next()) {
project_id = rs.getInt("project_id");
}
System.out.println(project_id);
the problem is why project_id returning me 0?
P.S. In database, i do have my project table fully inserted, and yes, i double checked value that are asked.
Change the code to be
while(rs.next()) {
int project_id = rs.getInt("project_id");
System.out.println(project_id);
}
I guess you will see no values (if there is a problem with the project_key)
Or many values the last one will be zero!
Try the following code to see if the result set returns any value
rs.first();
System.out.println(rs.getInt("project_id"));
If you don't see any value it means that the problem has to do with the query. Nothing is returned and the set is empty.
(I was going to comment this but I don't have enough reputation)
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
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");
}
I am creating a data centric webservice in Java for deployment to Glassfish. All of my methods so far are working correctly except for one.
I am attempting to assign a value from a result set to a variable to use in another SQL statement as per the below code. I am not sure if its possible, or if perhaps my SQL is wrong, but any ideas would be appreciated.
ResultSet rset1 = stmt1.executeQuery("SELECT *
FROM WorkOrder
WHERE WorkOrderID = '"+workOrderID+"'");
Integer custID = rset1.getInt(3);
ResultSet rset2 = stmt2.executeQuery("SELECT *
FROM Customer
WHERE CustID = '"+custID+"'");
Integer quoteID = rset1.getInt(2);
ResultSet rset3 = stmt3.executeQuery("SELECT *
FROM Quote
WHERE QuoteID = '"+quoteID+"'");
What you posted can and should be done in a single query - less complex, and less [unnecessary] traffic back & forth with the database:
SELECT q.*
FROM QUOTE q
WHERE EXISTS (SELECT NULL
FROM CUSTOMER c
JOIN WORKORDER wo ON wo.custid = c.custid
WHERE c.quoteid = q.quoteid
AND wo.workorderid = ?)
The reason this didn't use JOINs is because there'd be a risk of duplicate QUOTE values if there's more than one workorder/customer/etc related.
Additionally:
Numeric data types (quoteid, custid, etc) should not be wrapped in single quotes - there's no need to rely on implicit data type conversion.
You should be using parameterized queries, not dynamic SQL
You foget to invoke ResultSet.next().
if(rset1.next())
{
Integer custID = rset1.getInt(3);
....
}
The note provided by OMG Ponies was really important to take note of, but does not really answer the question. AVD was also correct. I've cleaned it up a bit and included prepared statements. Please use prepared statements. They will help you sleep at night.
PreparedStatement pstmt1 = con.prepareStatement(
"SELECT * FROM WorkOrder WHERE WorkOrderID = ?");
PreparedStatement pstmt2 = con.prepareStatement(
"SELECT * FROM Customer WHERE CustID = ?");
PreparedStatement pstmt3 = con.prepareStatement(
"SELECT * FROM Quote WHERE QuoteID = ?");
pstmt1.setInt(1, workOrderId)
ResultSet rset1 = pstmt1.executeQuery();
// test validity of rset1
if(rset1.next()) {
pstmt2.setInt(1, rset1.getInt(3))
ResultSet rset2 = pstmt2.executeQuery();
// test validity of rset2
if(rset2.next()) {
pstmt3.setInt(1, rset1.getInt(2))
ResultSet rset3 = pstmt3.executeQuery();
}
}