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");
}
Related
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 want to retrieve all the data from database, and at the same time, I want to know how many rows of data I get. And this is my SQL:
rs = s.executeQuery("SELECT COUNT(*), * FROM tblUser");
Is this a valid SQL statement? and after I retrieved all the data, how to set them into different variables? For example, I have a column called UserIDin the database, I can simply get it by using rs.getString('UserID'), but how to get the result of the COUNT(*)?
Your SQL is not valid. The ANSI standard way to do what you want uses window functions:
select count(*) over () as total_cnt,
u.*
from tblUser u;
This adds a new column to every row -- which seems to be what you want. There are other mechanisms, depending on the underlying database for doing this.
The results you request are not interrelated, so run two queries:
rs1 = s.executeQuery("SELECT COUNT(*) FROM tblUser");
rs2 = s.executeQuery("SELECT * FROM tblUser");
and retrieve the values (one only for rs1) the usual way.
You can do this to count the rows in resultset
String query = "Select * from tblUser";
rs = s.executeQuery(query);
public int getCount(ResultSet rs) {
int rows = 0;
while(rs.next()) {
i++;
}
return i;
}
This way you can get the resultset as well as count
Since you are already accessing the recordset within VBA probably the simplest was to return the count of the record set is to:
rs = s.executeQuery("SELECT * FROM tblUser");
If Not rs.EOF Then
' Important: You must move to the last record to
' obtain the count of the full recordset
rs.MoveLast
rsCount = rs.RecordCount
' Remember to Return to the First Record so that you can
' continue to use the recordset
rs.MoveFirst
End If
An alternative if your RDBMS doesn't support window functions
rs = s.executeQuery("SELECT B.cnt, U.*
FROM tblUser U,
(SELECT count(*) cnt FROM tblUser) B");
I have following String like that:String sql = "SELECT COL1, COL2, COL3 FROM SCHEMA.TABLE";
Now I need to get this value from String: SCHEMA.TABLE and this value is always changing. And also entire SQL is always changing.
How would I achieve this?
Don't know how to manipulate with different values?
This value is always after FROM and SQL may also have other values after FROM(ORDER BY, GROUP BY...)
SAMPLE SQL:
`SELECT ZGAR.ZGAR_ID, JARTI.ARTI_NAME, JZGAR.ZGAR_NAME, ZGAR.KAZG_ID, ZGAR.KZPO_ID, JZGAR.ZGAR_DESC FROM NETZGP.ZGANJEARTIKEL ZGAR LEFT JOIN NETZGP.J_ARTI JZGAR ON ZGAR.ZGAR_ID = JZGAR.ZGAR_ID LEFT JOIN NETZGP.J_ARTIKEL JARTI ON ZGAR.ARTI_ID = JARTI.ARTI_ID AND JZGAR.JEZI_ID = JARTI.JEZI_ID WHERE ZGAR.ARTI_ID = 1 AND JZGAR.JEZI_ID = 1 WITH UR`
The most succinct and reliable way is via regex:
String tableName = sql.replaceAll(".*FROM (\\S+).*", "$1");
This will also work when there's a WHERE clause after the table name.
Try with substring().
String result= queryString.substring(queryString.lastIndexOf(" ")+1);
gives the last part of the query.
If atleast FROM is there in every query
String[] result= s.split("FROM");
System.out.println(result[1]);
Use:String table= queryString.substring(queryString.lastIndexOf(" ")+1);
See String#substring().
If your sql query is changing frequently, you should use PreparedStatement instead of creating Statement many times.
Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement pst = con.prepareStatement("SELECT COL1, COL2, COL3 FROM ?");
String schemaTable = "<ANY_TEXT>";
p.setString(1, schemaTable);
ResultSet rs = p.executeQuery();
After that you can just change the schemaTable variable and again do p.setString(1, schemaTable); rs = p.executeQuery(); to get new results.
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();
}
}