ResultSet not open. Operation 'moveToInsertRow' not permitted. Verify that autocommit is OFF - java

i'm having a trouble with this error, when i clicked the button, it'll take the values of the labels and put it in the table from database
void showAll(){
try{
rs1 = stmt.executeQuery("SELECT * FROM BORROW_RETURN");
while(rs1.next())
{
String bookpp = rs1.getString("name");
String emailse = rs1.getString("email");
String booktee = rs1.getString("book_title");
String ser_no = rs1.getString("serial_no");
String borr = rs1.getString("borrowed");
String ret = rs1.getString("return");
loginModel3.addRow(new Object[]{bookpp, emailse, booktee, ser_no, borr, ret});
}}catch(SQLException err){
System.out.print(err);
}
}
and this is the connection to the connection to the database
void DoConnect1( ) {
try{
String host = "jdbc:derby://localhost:1527/Dafuq7";
String uName ="Dafuq7";
String uPass ="Dafuq7";
con = DriverManager.getConnection(host, uName, uPass);
//EXECUTE SOME SQL AND LOAD THE RECORDS INTO THE RESULTSET
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM borrow_return";
rs1 = stmt.executeQuery(sql);
}
catch (SQLException err) {
System.out.println(err.getMessage() );
}
}
and upon clicking the button the said error occurs,
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
String ema = jLabel20.getText();
String enm = jLabel21.getText();
String booknm = bttl.getText();
String snnnn = sernum.getText();
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dates = dateFormat.format(date_borr.getDate());
try {
rs1.moveToInsertRow();
rs1.updateString( "book_title", booknm );
rs1.updateString( "serial_no", snnnn );
rs1.updateString( "name", enm );
rs1.updateString( "email", ema );
rs1.updateString( "borrowed", dates );
JOptionPane.showMessageDialog(null, "HAHA");
loginModel3.addRow(new Object[]{names, booknm, snnnn, enm, ema, dates});
con.setAutoCommit(false);
System.out.println(con.getAutoCommit());
rs1.insertRow( );
stmt.close();
rs1.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM accounts";
rs1 = stmt.executeQuery(sql);
}
catch (SQLException err) {
System.out.println(err.getMessage() );
}
}

You are setting autoCommit to false after your queries are really committed. You need to set it false once after you open connection or before start executing your queries.
con = DriverManager.getConnection(host, uName, uPass);
//EXECUTE SOME SQL AND LOAD THE RECORDS INTO THE RESULTSET
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM borrow_return";
con.setAutoCommit(false);
rs1 = stmt.executeQuery(sql);

https://codedump.io/share/WK0Jtw7GEH3h/1/why-do-i-get-javasqlsqlexception-resultset-not-open-operation-39next39-not-permitted-java-derby-database
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

Related

How to fix "Declaration, final or effectively final variable expected" in a PreparedStatement.setString

The problem is that I am trying to set a wild card in a PreparedStatement but the setString statement is giving me the error above.
I have tried changing it to a setObeject statement with multiple different types like Types.VARCHAR. I have tried declaring the PreparedStatement in different places, and I have tried declaring 'name' in the method and in the class.
public String getTemplateText(String name) {
try (
Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT templateText FROM TEMPLATE WHERE " +
"templateTag = ?");
stmt.setString(1 , name); // this is the line that has the problem!
ResultSet rs = stmt.executeQuery()
) {
System.out.println("Set Text...");
String tempText = rs.getString("templateText");
return tempText;
} catch (SQLException e) {
e.printStackTrace();
}
return "";
}
/* this is the SQL code for the table that I am trying to query */
CREATE TABLE TEMPLATE
(
templateID INTEGER PRIMARY KEY IDENTITY(1,1)
, templateText TEXT
, templateTag CHAR(25)
);
You can't set the stmt parameter in your try-with-resources (because binding the parameter is void and not closable). Instead, you can nest a second try-with-resources after you bind the parameter. Like,
public String getTemplateText(String name) {
try (Connection conn = getConnection();
PreparedStatement stmt = conn
.prepareStatement("SELECT templateText FROM TEMPLATE WHERE " +
"templateTag = ?")) {
stmt.setString(1, name);
try (ResultSet rs = stmt.executeQuery()) {
System.out.println("Set Text...");
String tempText = rs.getString("templateText");
return tempText;
}
} catch (SQLException e) {
e.printStackTrace();
}
return "";
}

copying table from one database to another(sybase to mysql) in java

I have written code to connect to sybase database and mysql database and copy one table from sybase database to mysql database. My program is working fine and i am getting done what i waned but not in sufficient time. Sybase has total around 10000 rows in table that i am copying and it is taking around 4 mins to copy.
Can you guys suggest any improvement that can decrease the copying time.
Following is my code:
package jdbcexmple;
import java.sql.*;
import java.util.*;
public class Jdbcexmple {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/alarm";
static final String JDBC_DRIVER_SECOND = "net.sourceforge.jtds.jdbc.Driver";
static final String DB_URL_SECOND = "jdbc:jtds:sybase://11.158.251.19:4100/fmdb";
static final String USER = "root";
static final String PASS = "abc";
static final String USER_SECOND = "your";
static final String PASS_SECOND = "xyz";
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String a;
String b;
String c;
String d;
Connection conn = null;
Connection conn_2 = null;
PreparedStatement stmt = null;
try{
Class.forName(JDBC_DRIVER);
System.out.println("connecting to database mysql");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("connected to database successfully");
Class.forName(JDBC_DRIVER_SECOND);
System.out.println("connecting to database SYBASE");
conn_2 = DriverManager.getConnection(DB_URL_SECOND, USER_SECOND, PASS_SECOND);
System.out.println("connected to database successfully");
System.out.println("creating table in given database");
String sql = "CREATE TABLE newtable (CSN VARCHAR(255), IsCleared VARCHAR(255), ID VARCHAR(255), IP VARCHAR(255), PRIMARY KEY ( ID ))";
stmt = conn.prepareStatement(sql);
stmt.executeUpdate(sql);
System.out.println("created table in database");
Statement stmt_1= conn_2.createStatement();
String sql_1 = "select tbl_alm_log_2000000000.Csn, tbl_alm_log_2000000000.IsCleared, tbl_alm_log_2000000000.Id From fmdb.dbo.tbl_alm_log_2000000000 Where IsCleared = 0";
ResultSet rs = stmt_1.executeQuery(sql_1);
//below loop is taking 4 mins ie copying
while (rs.next())
{
a = rs.getString(1);
b = rs.getString(2);
c = rs.getString(3);
d = rs.getString(4);
sql = "INSERT INTO newtable values "+"("+"\""+a+"\","+"\""+b+"\","+"\""+c+"\","+"\""+d+"\""+")";
stmt = conn.prepareStatement(sql);
stmt.executeUpdate(sql);
System.out.println(a+" "+b+" "+c+" "+d);
}
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
conn_2.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
conn_2.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
Use Batch execution to insert data into mysql without execute one by one. You have already used PreparedStatement. That is fine.
There are two solutions:
Solution 1:-
String sql = "INSERT INTO newtable values (col1, col2,col3) values (?, ?, ?)";
Connection connection = new getConnection();
connection.setAutoCommit(false);
PreparedStatement ps = connection.prepareStatement(sql);
final int batchSize = 1000;
int count = 0;
while (rs.next()){
ps.setString(1, rs.getString(1));
ps.setString(2, rs.getString(2));
ps.setString(3, rs.getString(3));
ps.addBatch();
if(++count % batchSize == 0) {
ps.executeBatch();
}
}
ps.executeBatch(); // insert remaining records
connection.commit();
ps.close();
connection.close();
Your insert will be fast further with transaction handling. (connection.setAutoCommit(false); and connection.commit();)
http://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html#addBatch--
http://docs.oracle.com/javase/8/docs/api/java/sql/Statement.html#executeBatch--
http://viralpatel.net/blogs/batch-insert-in-java-jdbc/
Solution 2:-
rewriteBatchedStatements can be set with DB_URL this way.
jdbc:mysql://localhost:3306/alarm?rewriteBatchedStatements=true
So here rewriting to data bulk insert. Table lock once and indexes update once. This is another fastest way.
You can turn on the caching or use a connection pool. Using this, the first connection call will create a cache which will save time to query database.
OracleDataSource ods = new OracleDataSource();
// set cache properties
java.util.Properties prop = new java.util.Properties();
prop.setProperty("MinLimit", "2");
prop.setProperty("MaxLimit", "10");
// set DataSource properties
String url = "jdbc:oracle:oci8:#";
ods.setURL(url);
ods.setUser("hr");
ods.setPassword("hr");
ods.setConnectionCachingEnabled(true); // be sure set to true
ods.setConnectionCacheProperties (prop);
ods.setConnectionCacheName("ImplicitCache01"); // this cache's name
// We need to create a connection to create the cache
Connection conn = ds.getConnection(user, pass);
Statement stmt = conn1.createStatement();
ResultSet rset = stmt.executeQuery("select user from dual");
conn1.close();
ods.close();
For more information, check the implicit connection caching on: http://docs.oracle.com/cd/B19306_01/java.102/b14355/concache.htm#CACFIJJB

how to fix "This ResultSet is closed " error?

I want to use two sql query in my java code. the first query retain all row of table2 and the second one get it's rows one by one. I wrote follow code but it face to "This ResultSet is closed, it means rs ResultSet " error. How can I fix?
try{
String sqlSelectTable2 = "SELECT * FROM table2;";
ResultSet rs = stmt.executeQuery(sqlSelectTable2);
while (rs.next()) {
String strLineId = rs.getString(1);
String strPoints = rs.getString(2);
String sqlWithin = "SELECT ST_Within(ST_GeometryFromText('POINT( ),ST_GeomFromText('POLYGON((443425 4427680, 441353 4427680, 441368 4426075, 443762 4426149, 443425 4427680))', 4326));";
ResultSet rsWithin = stmt.executeQuery(sqlWithin);
} // end while ... **It get error when it is reading second ResultSet **
} catch (Exception e) {
System.out.println(e.getMessage());
}
You need to create separate PreparedStatement object for inner query
try{
String sqlSelectTable2 = "SELECT * FROM table2;";
ResultSet rs = stmt.executeQuery(sqlSelectTable2);
while (rs.next()) {
String strLineId = rs.getString(1);
String strPoints = rs.getString(2);
PreparedStatement preparedStatement = null;
String sqlWithin = "SELECT ST_Within(ST_GeometryFromText('POINT( ),ST_GeomFromText('POLYGON((443425 4427680, 441353 4427680, 441368 4426075, 443762 4426149, 443425 4427680))', 4326));";
preparedStatement = dbConnection.prepareStatement(sqlWithin);
ResultSet rsWithin = preparedStatement.executeQuery();
} // end while ... **It get error when it is reading second ResultSet **
} catch (Exception e) {
System.out.println(e.getMessage());
}

How to call parameterized stored procedure in jdbc

I need to call a parameterized stored procedure in java jdbc from sql server.
The stored procedure goes like this in sql
create proc patientreg
#id int
as
begin
select [patient_id],[Psurname], [pFirstname], [pMiddlename], [reg_date], [DOB], [Sex], [Phone_num], [Addr],[Email],[dbo].[fncomputeage](DOB) from [dbo].[Patient_registration] where [patient_id] = #id
end
please note dbo.fncompute(DOB) is a function
To call it in JDBC:
try{
String str = "{call patientreg(?)}";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbcdbc:GeneralHospital");
cstmt = con.prepareCall(str);
cstmt.setInt(1, Integer.parseInt(t.getText()));
cstmt.execute();
int pid = cstmt.getInt(1);
String sname = cstmt.getString(2);
String fname = cstmt.getString(3);
String mname = cstmt.getString(4);
String regdate = cstmt.getString(5);
String dob = cstmt.getString(6);
String sex = cstmt.getString(7);
String phonenum = cstmt.getString(8);
String address = cstmt.getString(9);
String email = cstmt.getString(10);
int age = cstmt.getInt(11);
l1.setText(sname+""+ fname+""+mname);
l3.setText(Integer.toString(pid));
l4.setText(regdate);
l5.setText(dob);
l6.setText(Integer.toString(age));
l7.setText(sex);
l8.setText(phonenum);
l9.setText(address);
l10.setText(email);
cstmt.close();
}
catch(Exception ex)
{
System.out.println("Error occured");
System.out.println("Error:"+ex);
}
After doing it this way it throwing an exception:
Error:java.sql.SQLException: Parameter 1 is not an OUTPUT parameter
there is a couple of problems with your code.
First, Don't use the jdbc odbc driver! It is unstable, and might not work correctly. Use Microsoft's own jdbc driver, or, even better, use jTDS, which is an excellent open source jdbc driver for Sql Server.
Second, the getInt, getString etc methods on CallableStatement is used to retrieve output parameters from the stored procedure. What you have is an ordinary resultset.
CallableStatement cstmt = con.prepareCall("{call patientreg(?)}");
// add input parameter
cstmt.setInt(1, someInteger);
// execute and get resultset.
ResultSet rs = cstmt.executeQuery();
// read resultset
while (rs.next()) {
int pid = rs.getInt(1);
String sname = rs.getString(2);
String fname = rs.getString(3);
// etc.
}
// remember to close statement and connection
try this
ResultSet rs = null;
PreparedStatement cs=null;
Connection conn=getJNDIConnection();
try {
cs=conn.prepareStatement("exec sp_name ?,?");
cs.setString(1, "val1");
cs.setString(2, "val2");
rs = cs.executeQuery();
ArrayList<YourClass> listYourClass = new ArrayList<YourClass>();
while (rs.next()) {
YourClassret= new YourClass();
ret.set1(rs.getString(1));
ret.set2(rs.getString(2));
ret.set3(rs.getString(3));
listaObjectX.add(ret);
}
return listYourClass ;
} catch (SQLException se) {
System.out.println("Error "+ se.getMessage());
se.printStackTrace();
} finally {
try {
rs.close();
cs.close();
con.close();
} catch (SQLException ex) {
//do ex.print
}
}

How to write prepareStatement in Java

i want to use getParameter to get in Strings and ints and put them in a database using prepareStatement and SQL. It gives me errors with setString and setInt.
try {
String id = request.getParameter("clientid");
String cname = request.getParameter("clientname");
String address = request.getParameter("address");
String phonemodel= request.getParameter("phonemodel");
String imei = request.getParameter("imei");
String problem = request.getParameter("problem");
String date2 = request.getParameter("date");
String comments1= request.getParameter("comments");
int clientid = Integer.parseInt(id);
int imeino = Integer.parseInt(imei);
// int date1 = Integer.parseInt(date2);
Statement pstmt;
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app" , "app");
pstmt=con.prepareStatement("Insert into movilapp(id,clientname,address,modle,imei,problem,date,comments) values(?,?,?,?,?,?,?,?)");
pstmt.setInt(1,clientid);
pstmt.setString(2,cname );
pstmt.setString(3,address);
pstmt.setString(4,phonemodel);
pstmt.setInt(5,imeino);
pstmt.setString(6,problem);
pstmt.setString(7, comments1);
pstmt.executeUpdate();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
You called con.prepareStatement to get a PreparedStatement, but then you assigned it to a variable of type Statement, so Java doesn't know that there is a PreparedStatement-specific method setString.
Assign it to an actual PreparedStatement variable, by changing the declaration type of pstmt from
Statement pstmt;
to
PreparedStatement pstmt;
*IF Use Statement Then its syntax is *
Statement stmt = null;
stmt = conn.createStatement( );
String sql = "UPDATE Employees set age=30 WHERE id=103";
stmt.executeUpdate(sql);
And for PreparedStatement it is
PreparedStatement pstmt = null;
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
psmt.setInt(1,30);
psmt.setInt(2,1003);
psmt.executeUpdate(SQL);
So change Statement pstmt; to PreparedStatement pstmt = null; And it will work.

Categories

Resources