SQLException - invalid cursor state - java

I am coding a simple CRUD Application in java and I have a Method to select Produkts that go with bills.
Here is my code:
public Rechnung selectProdukte(int target){
int tempProdukt;
int tempAnzahl;
try {
PreparedStatement ps1=hsqlmanager.getConnection().prepareStatement("SELECT produkt, anzahl from gekauftes_produkt " +
"WHERE rechnung= " + target + ";");
//ps1.setInt(1, target);
//Query 1wird executiert
PreparedStatement ps2 = hsqlmanager.getConnection().prepareStatement("SELECT * FROM rechnung WHERE id= " + target + ";");
//ps2.setInt(1, target);
ResultSet rs1 = ps1.executeQuery();
ResultSet rs2 = ps2.executeQuery();
Rechnung erg=new Rechnung();
erg.setId(rs2.getInt(1));
erg.setDatum(rs2.getDate(2));
erg.setSumme(rs2.getDouble(3));
while(rs1.next()){
tempProdukt=rs1.getInt(1);
tempAnzahl=rs1.getInt(2);
erg.addGekauftTupel(tempProdukt, tempAnzahl);
}
ps1.close();
ps2.close();
return erg;
} catch(Exception e) {
log.error("Fehler in DAO Rechnung - selectProdukte: " + e);
}
return null;
}
When I press the Button to execute the code I get:
java.sql.SQLException: invalid cursor state: identifier cursor not
positioned on row in UPDATE, DELETE, SET, or GET statement: ;
ResultSet is positioned before first row
I checked the db and all the tables and entities exist. So my question is:
What does that mean?
I appreciate your answer!!!
PS.: I am using hsql db!

you have not called rs2.next() before accessing erg.setId(rs2.getInt(1));

Related

Searching the Mysql database with Autocomplete on JTable using textfield

Could you please tell me what to add on my code so that when i type a letter in the textfield, before i finish typing the search result already start showing on jtable without waiting for me to type the whole word?
Below please find my code for key released event on the textbox. Thank you for your help.
private void jTextFieldSearchKeyReleased(java.awt.event.KeyEvent evt) {
try{
String selected=(String)jComboBoxSelected.getSelectedItem();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"
+ "employee_certificate","root","");
String sql="SELECT stuff.Emp_Id,stuff.Emp_Name, stuff.Department, "
+ "certificate.Cert_Code, certificate.Cert_Name,\n" +
"certificate.Cert, certificate.Vendor, certificate.Date_Taken, "
+ "certificate.Expiry_Date FROM stuff LEFT JOIN certificate"
+ " ON stuff.Emp_Id=certificate.Emp_Id "
+ "WHERE "+selected+" =? ORDER BY stuff.Emp_Name\n" ;
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1, jTextFieldSearch.getText());
ResultSet rs=pstmt.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
pstmt.close();
//con.close();
}
catch(Exception ex){ex.printStackTrace();}
}
After a two day struggle finally i got an answer...i just needed to use LIKE '%' as shown.No one should suffer as i did
private void jTextFieldSearchKeyReleased(java.awt.event.KeyEvent evt) {
try{
String selected=(String)jComboBoxSelected.getSelectedItem();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+ "employee_certificate","root","");
String sql="SELECT stuff.Emp_Id,stuff.Emp_Name, stuff.Department, "
+ "certificate.Cert_Code, certificate.Cert_Name,\n" +
"certificate.Cert, certificate.Vendor, certificate.Date_Taken, "
+ "certificate.Expiry_Date FROM stuff LEFT JOIN certificate"
+ " ON stuff.Emp_Id=certificate.Emp_Id "
+"WHERE "+selected+" LIKE ? ORDER BY stuff.Emp_Name\n" ;
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1,jTextFieldSearch.getText() + "%");
ResultSet rs=pstmt.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
pstmt.close();
con.close();
}
catch(Exception ex){ex.printStackTrace();}
}

looping error in java

When I run this code, the code shows errors. Please help me to fix this problem.
Here is my Java code:
public void kirim(){
try{
koneksi();
String data ="select count(Number) from pbk";
ResultSet rs1 = cn.executeQuery(data);
while (rs1.next()){
rs1.getString(1);
}
int banyakData=Integer.parseInt(rs1.getString(1));
for (int i=0; i<=banyakData ;i++){
String sqi = "select Number from pbk";
ResultSet rs = cn.executeQuery(sqi);
while(rs.next()){
rs.getString(sqi);
}
String sql="insert into outbox (DestinationNumber, TextDecoded, CreatorID) values ("
+ "'"+sqi +"',"
+ "'" + jTextArea1.getText()+ "',"
+ "'1'"
+ ")";
cn.executeUpdate(sql);
} JOptionPane.showMessageDialog(null, "Pesan terkirim");
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Pesan gagal terkirim");
System.out.println(e.getMessage());
}
}
Here is stack trace output:
After end of result set
Change your code to
ResultSet rs1 = cn.executeQuery(data);
int banyakData;
while (rs1.next()){
banyakData= rs1.getInt(1);
}
and remove
int banyakData=Integer.parseInt(rs1.getString(1));
With you approach you have already iterated through the resultset and after the completition of the while loop you are again fetching from resultset giving you the error.
And also simply doing rs.getString(sqi); and rs1.getString(1); in a while loop doesnt make any sense if you dint put the result in any variable btw sqi is not a valid parameter.

How to truncate a Postgresql's table from JDBC

I have a Postgresql database and I want to truncate some tables using JDBC. How do I do that?
This is what I tried, but none worked... without even any error being reported:
Using CallableStatement.
try (Connection connection = getConnection();
CallableStatement statement = connection.prepareCall("TRUNCATE " + tableName)) {
return statement.execute();
}
Using Statement.
try (Connection connection = getConnection();
Statement statement = connection.createStatement()) {
return statement.execute("TRUNCATE " + tableName);
}
Using PreparedStatement.
try (Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement("TRUNCATE " + tableName)) {
return statement.execute();
}
After the truncate, I need to commit:
try (Connection connection = getConnection();
Statement statement = connection.createStatement()) {
int result = statement.executeUpdate("TRUNCATE " + tableName);
connection.commit();
return result;
}
From the documentation:
TRUNCATE is transaction-safe with respect to the data in the tables: the truncation will be safely rolled back if the surrounding transaction does not commit.
You may run into issues if the table has dependencies. If so, truncate the parent tables first, and also use the CASCADE option.
Connection connection = getConnection();
try {
PreparedStatement statement = connection.prepareStatement("TRUNCATE " + parentTable1, parentTable2, ... + " CASCADE");
try {
return statement.execute();
} finally {
statement.close();
}
} finally {
connection.close();
}
First, if you are truncating a table, you probably want to also RESTART IDENTITY (in addition to possibly doing CASCADE, as John Hogan mentioned).
Second, as far as doing a connection.commit(), the assumption is that you have autocommit set to OFF. My Postgres was set up with it set to ON (apparently, that is sometimes the default).
If it is set to ON, then calling the commit is unnecessary, and will result in the error:
"org.postgresql.util.PSQLException: Cannot commit when autoCommit is enabled."
Third, you may not have permission to truncate a table (or restart identity). In that case, you will need to:
DELETE from your_table
SELECT setval('your_table_id', 1)
The following worked for me:
public String truncateTable(String tableName, boolean cascadeFlag) {
String message = "";
try {
connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
String truncation = "TRUNCATE TABLE yourSchema." + tableName + " RESTART IDENTITY" + (cascadeFlag ? " CASCADE" : "");
System.out.println("truncateTable: Executing query '" + truncation + "'.");
int result = statement.executeUpdate(truncation);
// connection.commit(); // If autocommit is enabled (which it is for our DB), then throws exception after truncating the table.
statement.close();
connection.close();
} catch (SQLException sqlex) {
message = "Could not truncate table " + tableName + ". " + sqlex.getMessage();
System.err.println(message);
sqlex.printStackTrace();
}
return message;
}
Also:
public int deleteResetTable(String tableName, String fieldName) {
int affectedRows = 0;
try {
connection = DriverManager.getConnection(url, username, password);
String sql = "DELETE FROM yourSchema." + tableName;
PreparedStatement preparedStatement = connection.prepareStatement(sql);
affectedRows = preparedStatement.executeUpdate();
System.out.println("Deleted " + affectedRows+ " rows from table " + tableName + ".");
sql = "SELECT setval('yourSchema." + fieldName + "', 1)";
preparedStatement = connection.prepareStatement(sql);
affectedRows = preparedStatement.executeUpdate();
System.out.println("Reset " + affectedRows+ " values from table " + tableName + ".");
} catch (SQLException ex) {
System.out.println("Failed to delete rows from " + tableName + " " + ex.getMessage());
}
return affectedRows;
}

Error while getting resultset

I have a class in which i am getting resultset from the database:
public ResultSet GetDataFromDB() {
ResultSet resultset = null;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
System.out.println("Connecting to the database...");
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin:#host:1521:DBname", "user123","pass123");
Statement statement = connection.createStatement();
resultset = statement.executeQuery("select * from tablename");
while (resultset.next()) {
System.out.println(resultset.getInt(1) + " " +
resultset.getInt(2) + " " +
resultset.getInt(3) + " " +
resultset.getString(4));
}
// statement.close();
//connection.close();
} catch (Exception e) {
System.out.println("The exception raised is:" + e);
}
return resultset;
}
In this classs i am able to print the data which i am getting in resultset. but when i tried to get this resultset in another class:
Classname obj= new Classname();
ResultSet tempResultSet = obj.GetDataFromDB();
System.out.println("Records Exist "+tempResultSet.next()); <-----false
I am not getting any data here.
also there is no datatable here in java like in .net so that i can use that...Please concern
thanks
while (resultset.next()) {
You already read all of the data from the ResultSet in this loop.
ResultSet is a single-use, forward-only view of the data; you can only iterate it once.

JDBC's rs.getString() won't return the value of the query result

I have some problems with JDBC's rs.getString("column_name") basically it would not assign the value recieved from the query result, I have a String ris which is supposed to get the row name from rs.getString, for semplicity of the question I'm using ris and my query returns only one row. This is the code:
//It returns null, or any other values I use to initialize the variable
String ris=null;
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")";
ResultSet rs = st.executeQuery(q);
if (!rs.last()) {
ris = "no";
}
else {
//This is the place where I'm having problems
while(rs.next()){
//ris is supposed to get the name of the query result having column "nome"
ris=rs.getString("nome");
}
}
conn.close();
} catch (Exception e) {
ris = e.toString();
}
return ris;
I semplified the code, so it would be easy to focus on where the problem is.
Thanks in advance!
if (rs.last())
while (rs.next())
That won't work, because after you have called last , you are at the last row and next will always return false (it would return true and take you to the next row if there was one left).
And please use a prepared statement with bind variables!
And finally close ResultSet and Connection (or use Jakarta Commons DbUtils).
try this, just remove the rs.last() call in the if condition.. also i agree with #Thilo about using prepared statements.
String ris=null;
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")";
ResultSet rs = st.executeQuery(q);
rs.first(); // go to first record.
//This is the place where I'm having problems
while(rs.next()){
//ris is supposed to get the name of the query result having column "nome"
ris=rs.getString("nome");
}
}
conn.close();

Categories

Resources