java.sql.SQLException: ResultSet is from UPDATE. No Data. - java

(the Stored Procedure runs perfectly in MySQL Workbench and also retrieves the Rows)
Here is My Code :
ConnectionManager cm = new ConnectionManager();
java.sql.CallableStatement cstmt = null;
try
{
connect = cm.getConnection();
connect.createStatement();
String SQL = "{call getReportDetails ('"+ emailId +"','"+password+"')}";
cstmt = connect.prepareCall(SQL);
rs = cstmt.executeQuery(SQL);
int i = 0;
while(rs.next())
{
String element1 = rs.getString("description");
// -- some code --
}
}
catch(Exception e)
{
e.printStackTrace();
}

Delete the line with createStatement.
And (the error) do not use SQL as parameter of executeQuery.
(The overloaded version with an sql parameter is for the immediate, non-prepared statement version.)
Further close statement and result set; try-with-resources will do nice here.
try (CallableStatement cstmt =
connect.prepareCall"{call getReportDetails (?, ?)}")) {
cstmt.setString(1, emailId);
cstmt.setString(2, password);
try (ResultSet rs = cstmt.executeQuery()) {
int i = 0;
while (rs.next())
{
String element1 = rs.getString("description");
// -- some code --
}
}
}
In the general case for stored functions you might need to specify the result yourself:
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.registerOutParameter(2, Types.VARCHAR);
rs.getString(2);
But here you have a ResultSet.

CallableStatement cs = null;
try {
cs = connectionObject.prepareCall("{call getReportDetails (?, ?)}");
cs.setString(1, emailId);
cs.setString(2, password);
cs.execute();
ResultSet rs = cs.getResultSet();
while (rs.next()) {
System.out.println(rs.getString("columnLabel"));
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
//close statements
}

Related

Syntax for SQL statement using mysql database

public void insertTags(Elements[] elements) {
Connection con = (Connection) DbConnection.getConnection();
try {
String sql = "insert into htmltags(source) values(?),(?),(?)";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, elements[0].toString());
ps.setString(2, elements[1].toString());
ps.setString(3, elements[2].toString());
int rs = ps.executeUpdate(sql);
System.out.println("Data inserted" + rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
is this a valid syntax for Prepared statement.
This is your problem:
int rs = ps.executeUpdate(sql);
From the JavaDoc we see that PreparedStatement#executeUpdate() does not take any parameters. The reason is that we already passed the query earlier when preparing the statement. Your code should be this:
int rs = ps.executeUpdate(); // no parameter
Also no need to cast the result of prepareStatement to PrepareStatement
To insert multiple values, I don't thing using values(?),(?),(?) is the right syntax, instead use a loop, or for better way you can use batch :
String sql = "insert into htmltags(source) values(?)";
try (PreparedStatement ps = con.prepareStatement(sql);) {
for (Elements element : elements) {
ps.setString(1, element.toString());
ps.addBatch();//Add a new batch for each Element
}
int[] result = ps.executeBatch();//Submits a batch of commands to the database
} catch (SQLException e) {
e.printStackTrace();
}

Speeding up sql inserts on postgresql with JDBC?

I have two methods below for checking if a match is in the database and if not if would call the insert method. My program has to go through thousands of rows and it takes a very long time. Am I doing this incorrectly? Anything I can do to significantly make this faster?
public Boolean isMatchIdInDatabase(String matchId) throws SQLException
{
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
Boolean exists = false;
try
{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(url, props);
pst = conn.prepareStatement("SELECT COUNT(*) FROM match where match_id = ?");
pst.setString(1, matchId);
rs = pst.executeQuery();
while (rs.next())
{
exists = rs.getBoolean(1);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
pst.close();
rs.close();
conn.close();
}
return exists;
}
public Boolean insertMatchId(String matchId, String name, Timestamp birthdate, String bio, String accountId) throws SQLException, ClassNotFoundException
{
Connection conn = null;
PreparedStatement pst = null;
Boolean exists = false;
try
{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(url, props);
pst = conn.prepareStatement("INSERT INTO match (match_id, name, birthdate, bio, account_id) values(?, ? , ?, ?, ?)");
pst.setString(1, matchId);
pst.setString(2, name);
pst.setTimestamp(3, birthdate);
pst.setString(4, bio);
pst.setString(5, accountId);
pst.executeUpdate();
}
finally
{
pst.close();
conn.close();
}
return exists;
}
Are you calling first isMatchIdInDatabase then insertMatchId for many records?
Possible duplicate: Efficient way to do batch INSERTS with JDBC
It is an expensive operation to open a connection and query for a single record. If you do that thousands of times, it gets very slow. You should try to restructure your query so that you only use one SELECT. Then you can collect the records which you have to insert and doing it with batch insert.
You could try changing your SQL query that inserts the row to insert only if the row isn't in the database by using WHERE NOT EXISTS.
This post seems to be relevant - I know it's for MySQL instead of PostgreSQL but the principles should be the same.
MySQL Conditional Insert

Database Java Bean SQL Statement

In my database bean I have a section of code which is below :
public Integer getTotalOrgPoints() {
try {
PreparedStatement stmt = ConnectionHandler.getConnection().prepareStatement(QUERY_TOTAL_ORG_SCORE);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
totalOrgPoints = rs.getInt(1);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return totalOrgPoints;
}
For the statement QUERY_TOTAL_ORG_SCORE if I use
SELECT SUM(users.score)
FROM user_organisation_relationships
INNER JOIN users
ON user_organisation_relationships.user_id = users.id
WHERE organisation_id = 1
It will return the value for that organisation but if I use
SELECT SUM(users.score)
FROM user_organisation_relationships
INNER JOIN users
ON user_organisation_relationships.user_id = users.id
WHERE organisation_id = ?
I get nothing does anyone know why this is happening for me?.
Add this line to bind values for prepared statement before executequery
stmt.setInt(1, 1);
Modified:-
PreparedStatement stmt = ConnectionHandler.getConnection().prepareStatement(QUERY_TOTAL_ORG_SCORE);
stmt.setInt(1, 1);
ResultSet rs = stmt.executeQuery();

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

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.

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
}
}

Categories

Resources