Ms access "invalid record set status" error - java

I connect to my access database successfully and my sql is works and after these i have a result set. Code is below:
Statement stmt = con.createStatement();
String sqlStr ="select max(ID) from GuestBook ";
ResultSet rset = stmt.executeQuery(sqlStr);
But when i want to get value from resultset like this;
int id = rset.getInt(1);
or
int id = rset.getInt("ID");//or "max(ID)"
I have a sql exception.
Exception is "invalid record set status"
How can i solve this problem?

A column name of "Expr1000" will be generated for max(ID). But I think that it is better to use an As clause to give it a well defined alias.
You must call rset.next() in order to move to the first row, because initially, the cursor is positioned before the first row.
Statement stmt = con.createStatement();
String sqlStr ="SELECT max(ID) As LastID FROM GuestBook";
ResultSet rset = stmt.executeQuery(sqlStr);
int id = 0;
if (rset.next()) {
id = rset.getInt("LastID");
// OR
id = rset.getInt(1);
}

Related

Error "java.sql.SQLException: ORA-04054" JDBC-ORACLE

My code looks as follows:
ResulSet rs = stmt.executeQuery("select passwd from mrs_user where email="+mail_id);
String usr_paswd = rs.getString(1);
But the error is as follows:
java.sql.SQLException: ORA-04054: database link G.COM does not exist
mail_id=dk#g.com
First, String should be between to quotes 'mail_id', but this way is not secure it can cause SQL Injection or syntax error instead you can use PreparedStatement.
Second, you still not get any result, you have to call rs.next() before to moves the cursor to the next row (read about Retrieving and Modifying Values from Result Sets).
Code example
String usr_paswd = null;
try (PreparedStatement stmt = connection.prepareStatement(
"select passwd from mrs_user where email=?")) {
stmt.setString(1, mail_id);
ResulSet rs = stmt.executeQuery();
if(rs.next()){
usr_paswd = rs.getString(1);
}
}

How to get current row inserted

I have a table, and in it I have
UsernameID,UniqueID, component, coorX, coorY, coorX2, coorY2.
The UniqueID is created by Auto Increment. I want to get the current row after I insert into my table. How do I insert the current row in MySQL? I'm using Java.
In php they used
mysql_insert_id()
Can you give me an example of a script to insert the current row in MySQL using Java?
It's JDBC standard feature, see Statement.executeUpdate(String sql, int autoGeneratedKeys), example:
Statement stmt = conn.createStatement();
stmt.executeUpdate("insert into t1 (UsernameID) values (1)", Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
long id = rs.getLong(1);
You can also use PreparedStatement for the same.
String ColumnsArray[] = {"columnName"};
String sqlQuery = " " // write your insert query here
PreparedStatement pstmt = conn.prepareStatement(sql,ColumnsArray);
pstmt.setString(1, "anyvalue");
pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
if(rs.next())
long key = rs.getLong(1);

How to resolve the id from MySQL DB into a variable

Is is possible to get the id from a MySQL table and "save" it into a variable on JDBC?
In my program, I have a JTextfield in which the user gives a ticket which will be stored on a MySQL DB. Everytime he gives a ticket, I want to get the id from my db where the ticket was inserted and not print in on teminal, but resolve it into a variable and use it on other classes also. I need it for other classes.
Is is possible?
Something like this ?
statement.executeUpdate();
ResultSet generatedKeys = statement.getGeneratedKeys();
long generatedId= 0L;
if (generatedKeys.next()) {
generatedId = generatedKeys.getLong(1);// here is your generated Id ,
}
Something like that?
PreparedStatement st;
st = con.prepareStatement("SQL STATAMENT", "HERE COLUMN NAME FROM TABLE") VALUES(?)",Statement.RETURN_GENERATED_KEYS);
st.setString(1,"Binded String Veriable");
st.executeUpdate();
ResultSet rs = st.executeQuery("select last_insert_id() as id from "HERE TABLE NAME"");
if(rs.next()){
int lastId = Integer.parseInt(rs.getString("id"));
Use PrpearedStatment to prevent SQL Injection for example:
st = con.prepareStatement("INSERT INTO component(user) VALUES(?)", Statement.RETURN_GENERATED_KEYS )
st.setString(1,username)
Here you have how last_insert_id() works: JDBC LAST INSER ID AND OTHER

How to compare Two Resultset Columns values in Java?

Can anyone tell me how I can compare two resultset values? Only getting error in if statement, but the rest is working.
Statement s = con.createStatement();
Statement stmnt = con.createStatement();
String query = "select * from tbl_product";
s.execute(query);
ResultSet rs = s.getResultSet();
while(rs.next())
{
String strOuter=rs.getString(2);
System.out.println(strOuter);
String query1 = "select * from PRODUCTS_AJ";
stmnt.execute(query1);
ResultSet rs1 = stmnt.getResultSet();
while(rs1.next())
{
System.out.println("-------"+rs1.getString(2));
if(rs.getString(2).equals(rs1.getString(2)))// Getting Error here for this line
{
System.out.println("Found");
}
}
}
java.sql.Exception data not found
This types of error occurs when you try to read same column of the same cursor multiple times. And what you encountered is a typical scenario. Just store the string temporarily like bellow:
String col3 = rs1.getString(2);
and use col3 instead of rs1.getString(2), whenever needed.
System.out.println("-------"+ col3);
if(col3.equals(rs1.getString(2)))
{
...
You cannot re-read a column value again. So, copy it in a local variable for logging.
String val = rs1.getString(2);
System.out.println("-------" + val);
if (rs.getString(2).equals(val)) {
What you could possibly do is
use SQL where clause
String query1 = "select * from PRODUCTS_AJ where fieldNmae = 'something'";
ResultSetMetaData rsm = rs.getMetaData();
int colCount = rsm.getColumnCount();
if (colCount > 1)
{
// found
}
For ResultSetMetaData
or possibly do
ResultSet rsOLD = null;
ResultSet rs = s.getResultSet();
// rs will be new ResultSet
while(condition)
{
// check from second row (maintain if case)
.
.
.
// end of loop
rsOLD = rs;
}
Ok ! This is a typical error while using JDBC-ODBC bridge driver with MS Access. I have experienced.I solved it in following way. Retrieving the same data more than once from the result set.
Please try like this
ResultSet rs = s.getResultSet();
String str=rs.getString(2);
Use this string to compare
str.equals(rs2.getString(2)
Thanks!
rs.getSting(2) is executed the number of row times of rs1 in the while loop of rs1. You may not have the that many number of rows in rs as rs1.

How to check if a record with a specific primary key exists in a MySql table from JDBC

How can i find out, from a Java program using JDBC if my table has a record with a specific primary key value? Can i use the ResultSet somehow after i issue a SELECT statement?
Count might be a better idea for this case. You can use it like so:
public static int countRows(Connection conn, String tableName) throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName + " WHERE.... ");
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
} finally {
rs.close();
stmt.close();
}
return rowCount;
}
Taken from here.
You can do something like
private boolean hasRecord(String id) throws SQLException {
String sql = "Select 1 from MyTable where id = ?";
PreparedStatement ps = dbConn.prepareStatement(sql);
ps.setString(1,id);
ResultSet rs = ps.executeQuery();
return rs.next();
}
You can do that in four steps.
Write SQL. Something like select count(1) from table where column = 34343 will do.
Learn how to get connection using JDBC.
Learn about PreparedStatements in Java.
Learn how to read values from ResultSet.
select case
when exists (select 1
from table
where column_ = '<value>' and rownum=1)
then 'Y'
else 'N'
end as rec_exists
from dual;

Categories