java - ResultSet displaying as String - java

I am using the ucanaccess tool to interact with my access database, but I do not know how to display or store the resulting ResultSets as Strings.
Edit: I have tried =System.out.println(resultSetId.getString(1)); but that only returns errors.
ResultSet resultSetId;
String msAccDB = "D://Computer Science//passManager//src//Manager.accdb";
String dbURL = "jdbc:ucanaccess://" + msAccDB;
connection = DriverManager.getConnection(dbURL);
statement = connection.createStatement();
resultSetId = statement.executeQuery("SELECT ID FROM Passwords WHERE ID =
\""+identifier+"\";");
System.out.println(resultSetId.getString(1));
Gives the error Exception in thread "main" net.ucanaccess.jdbc.Ucanaccessenter code hereSQLException: invalid cursor state: identifier cursor not positioned on row in UPDATE, DELETE, SET, or GET statement: ; ResultSet is positioned before first row
Edit: Adding the .next() fixed it, thanks!

ResultSet is positioned before first row
When executeQuery returns the ResultSet it is not pointing at a row of data. You need to call resultSetId.next() in order to retrieve each row. That is often done in the context of a while loop when the ResultSet is expected to return more than one row, e.g.,
while (resultSetId.next()) {
System.out.println(resultSetId.getString(1)); // print value from each row
}
but you can simply call it once if you only expect a single row, e.g.,
if (resultSetId.next()) {
System.out.println(resultSetId.getString(1));
} else {
System.out.println("The ResultSet contained no rows.");
}

Related

SQL statement returns a resultset on an empty table

String sql = "Select MAX(ORDERLINEID) From ORDERLINESTABLE";
ResultSet rst;
rst = stmt.executeQuery(sql);
if(rst.next())
{
next = rst.getInt("ORDERLINEID");
next++;
}
I have a table called ORDERLINESTABLE in my database which is currently empty. I have run the above code with the aim is to get the highest integer stored in the ORDERLINEID column allowing me to increment it when adding items to the database.
I expected this query to return nothing as the table is empty but when debugging I noticed that the search is returning true for the rst.next() method.
Does anyone have any idea why this would be? I have looked at the resultset.next() documentation and as far as I can see it should return false.
When in doubt, look at your data. Here is a sample query from any db engine.
select max(field) maxValue
from table
where 1=3
It will yield
maxValue
Null
In other words, your query is returning one record with a value of null.
It is much better to fetch the ORDERLINEID filled in by the database after the INSERT statement. Make the column ORDERLINEID of type INT AUTOINCREMENT.
String sql = "INSERT INTO ORDERLINESTABLE(xxx, yyy) VALUES (?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
stmt.setString(1, xxx);
stmt.setInt(2, yyy);
int updateCount = stmt.executeUpdate(); // 1
try (ResultSet id = stmt.getGeneratedKeys()) {
if (id.next()) { // 'if' as just 1 row inserted.
int orderLineId = id.getInt(1); // 1 key per row.
}
}
}
Java has a database independent way to fetch the generated keys of an INSERT. That is a lot safer than taking the MAX afterwards or before, in a multi-user environment.
Scenarios for wrong IDs are numerous in a multiuser environment:
first SELECT
second SELECT
second increment for new ID
first increment for new ID
first INSERT
second INSERT

Postgresql with java: query produced no result after insert

I write a little program to admin my video collection.
/*
insert new data set into the table
*/
int next = 0;
rs = st.executeQuery("Select max(category_id) from category;");
if (rs.next()) {
next = rs.getInt(1) + 1;
System.out.println(next);
}
String query = "INSERT INTO category VALUES (" + next + ", 'Mystics', now());";
rs = st.executeQuery(query);
//on this place is the exception thrown
// this will not execute anymore
rs = st.executeQuery("DELETE FROM category WHERE name = 'Mystics';");
The program can select on tables, make joins but insert make trouble.
I try to insert some new data in my table (see Java-code). After the second test the output show me that the data was inserted. But after Insert was an exception thrown.
1 & 2 are the tests from yesterday and today. (3) was inserted but not selected yet.
1 Mystics 2015-07-05
2 Mystics 2015-07-06
3
org.postgresql.util.PSQLException: query produced no result.
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:287)
at postgre_java.Zetcode.main(Zetcode.java:55)
do you have some advises for me?
Do not manipulate data with read statements!
If you want to insert, update, delete data in db use
Statement stmt = conn.createStatement();
stmt.executeUpdate(SQL);
executeQuery returns resultset, but all that INSERT, UPDATE, DELETE can return is number of affected rows and that is what executeUpdate is returning.
And never, never, never*100 use string concatenation in SQL use Prepared statements!
In Java, you use executeQuery for a SELECT statement or some other statement which returns something. If you want to execute an INSERT, UPDATE or DELETE without returning something, you should use executeUpdate().
Statement#executeUpdate() is meant for that purpose
String query = "INSERT INTO category VALUES (" + next + ", 'Mystics', now());";
int noOfRows= st.executeQuery(query)
but it doesnt return a ResultSet , rather the no of rows affected that you could store into an Integer
Also your is highly vulnerable to Sql injection , try using the PreparedStatements to safeguard your code

How to get all values in one column in mysql

I'm trying to create a method that return with all values in the selected column in mysql
so can anyone tell me the used method in java
this method returns with just the first value in the column ::
public ArrayList<String> GetChair(String Class) throws SQLException{
openconnection();
String querychair = "SELECT * FROM hema.flight_usa WHERE free = 1 and class='"+Class+"'";
Statement stm=(Statement) con.createStatement();
ResultSet rs;
rs = stm.executeQuery(querychair);
if(rs.next()){
arr.add(rs.getString("chair_id"));
}
return arr;
}
while(rs.next())
{
arr.add(rs.getString("chair_id"));
}
This gives you the value of the first column for all the rows in your rs
Like the comment says, you are reading the values in the if statement. That will only return the first result, if there is anything in the result set. Read it in a while loop, until the result set is empty.

prepared statements and result sets - Java null pointer exception

Overview: Trying to connect to a MS Access DB to return a result set into a jtable.
Issue: java null pointer exception
Code:
package sundata;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Database {
public String strMIGID;
public String strEBID;
public String strSUN;
public String[][] objIDList;
//CONNECTION INFO
private Connection con;
private String strDBCon="jdbc:ucanaccess://C:/Users/Luke/Documents/MainDB.mdb";
public String strEXMessage;
public int CreateConnection(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(strDBCon);
return 1;
}catch(Exception ex){
ex.printStackTrace();
strEXMessage=ex.getMessage();
return 2;
}
}
public int CloseConnection(){
try{
con.close();
return 1;
}catch(Exception ex){
ex.printStackTrace();
strEXMessage=ex.getMessage();
return 2;
}
}
public int GetMIGIDRecord(String strMIGIDRef){
try{
System.out.println("Connecting to database using MIGID");
String strSQLString = "Select * from tblSuppliersData where Supplier1 = ?";
PreparedStatement preStatement = con.prepareStatement(strSQLString, ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
//SETTING FIRST CONDITION OF PREPARED STATEMENT IE ?
preStatement.setString(1, strMIGIDRef);
//EXECUTE QUERY
preStatement.executeQuery();
//RETURNS QUERY RESULTS INTO RESULT SET
ResultSet rs = preStatement.getResultSet();
//CHECK TO MAKE SURE SOME RECORDS ARE RETURNED
rs.last();
//IF CHECKS TO MAKE SURE RECORDS
if(rs.getRow()==0){
rs.close();
preStatement.close();
return 3;
}
//RECORDS NUMBER OF RECORDS
int iNoRecords = rs.getRow();
//CREATING 2D ARRAY WITH NO RECORDS (ROWS) AND TWO COLUMNS
String strTempdata[][] = new String [iNoRecords][3];
//MOVES BACK TO BEFORE FIRST RECORD
rs.beforeFirst();
//TRANSPOSES RS IN TO ARRAY
int i = 0;
while (rs.next()){
strTempdata[i][0]= rs.getString("MIGID");
strTempdata[i][1]= rs.getString("EBID");
strTempdata[i][2]= rs.getString("SUN");
i++;
}
objIDList = strTempdata;
//CLOSES CONNECTIONS
rs.close();
preStatement.close();
System.out.println("Connection complete");
return 1;
}catch(Exception ex){
ex.printStackTrace();
strEXMessage=ex.getMessage();
return 2;
}
}
I have a form that grabs the strMIGIDREF which I can paste code from if needs be, but I think it's not the issue here.
This is the error I'm getting, I've pasted the first bit and can paste more if required.
Connecting to database using MIGID
java.lang.NullPointerException
at sundata.Database.GetMIGIDRecord(Database.java:63)
at sundata.MainForm.MIGIDSearch(MainForm.java:141)
at sundata.MainForm.jmenuMIGIDSearchActionPerformed(MainForm.java:337)
at sundata.MainForm.access$000(MainForm.java:6)
at sundata.MainForm$1.actionPerformed(MainForm.java:58)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
Line 63 is
//CHECK TO MAKE SURE SOME RECORDS ARE RETURNED
rs.last();
I have tried a number of solutions I've found on Google and no joy as of yet. I have tried a test bit of code that checks connections and such and that seemed to work fine it's just when I'm trying use preparedstatement it seems to go a miss.
ResultSet rs = preStatement.getResultSet(); just keeps saying it's value is null and so is getMaxRows.
I'm using Netbeans IDE 7.4 and JAVA SE SDK 7
You are getting a NullPointerException because you are mis-using the executeQuery method:
//EXECUTE QUERY
preStatement.executeQuery();
//RETURNS QUERY RESULTS INTO RESULT SET
ResultSet rs = preStatement.getResultSet();
The first line of code executes the SQL query and returns a ResultSet object, which you simply discard (because you don't assign it to anything). The second line of code attempts to retrieve the ResultSet for the PreparedStatement, but it has already been retrieved (and discarded) by the previous line, so getResultSet returns null.
Instead, you should simply do
ResultSet rs = preStatement.executeQuery();
Additional notes:
Omit the Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); statement because (1) It is irrelevant: UCanAccess does not use ODBC, and (2) Class.forName statements are almost never required any more (and UCanAccess doesn't need one at all).
Don't use rs.last() to test if rows were returned. Instead, simply call rs.next() immediately after the ResultSet is returned. If rs.next() returns true then the ResultSet contains rows (and you are now pointing at the first one). If rs.next() returns false then no rows were returned. rs.last() followed by rs.beforeFirst() will not work correctly with the default ResultSet type, which is ResultSet.TYPE_FORWARD_ONLY.

Query showing extra row

<%
String qTotal = "SELECT MsThread.ID, MsThread.ThreadName, Count(MsThread.ThreadName) AS TotalPost, ThreadCategory FROM MsThread LEFT OUTER JOIN MsPosts ON MsThread.ThreadName = MsPosts.ThreadName GROUP BY MsThread.ID, MsThread.ThreadName, MsThread.ThreadCategory;";
ResultSet rs = stmt.executeQuery(qTotal);
int size = 0;
while(rs.next())
{
out.print(size++);%><br/><%
}
rs.first();
out.println(rs.getString("id"));
rs.next();
out.println(rs.getString("id"));
rs.next();
out.println(rs.getString("id"));
if(!rs.next())
{
out.println("no data");
}
else
out.println(rs.getString("id"));
%>
Guys, here's what happened, when i tried to run the query it shows 3 result (http://s29.postimg.org/6qiv9kc9j/ss_forum.png) but when i run the
while(rs.next())size++;
it returns 4, and when i try to show the data, it gives me invalid cursor state, so is there anything wrong with my query?
thanks
The default sensitivity of a ResultSet is TYPE_FORWARD_ONLY, which means that it cannot be scrolled; you cannot call any of these methods that move the cursor -
previous
first
last
beforeFirst
afterLast
relative(int rows)
absolute(int row)
Except next, your ResultSet cannot be scrolled. If your resultset if created with default sensitivity then they can not be scrolled using rs.first(); after moving to last end via rs.next() in while statement.
but when i run the while(rs.next())size++; it returns 4,
When a ResultSet object is first created, the cursor is positioned before the first row, so you are getting 4.
Thanks

Categories