SQLException: This ResultSet is closed - java

I am trying to compare values from three Resultset, but there seems to exception wen I try to run it.
Could someone help me on where am going wrong. I will appreciate any help. Here's the code snippet that's throwing the error:
java.sql.Connection connDB = null;
java.lang.Object[] reconciledPaymentDetails = null;
java.util.Vector shiftsVector = new java.util.Vector(1, 1);
String status = "";
try {
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
}
try {
connDB = DriverManager.getConnection("jdbc:postgresql://" + hostName + ":" + portNumber
+ "/" + dbName, userName, password);
System.out.println("Connection established : [" + connDB.toString() + "]");
java.sql.Statement pstmt = connDB.createStatement();
java.sql.Statement pstmtShifts = connDB.createStatement();
java.sql.ResultSet rset = pstmt.executeQuery("SELECT DISTINCT payment_mode,
transaction_type, credit FROM ac_cash_collection WHERE shift_no = '" + shiftNumber +
"'");
while (rset.next()) {
java.sql.ResultSet rsetShifts = pstmtShifts.executeQuery("SELECT DISTINCT amount,
shift_amount FROM ac_shift_collections WHERE shift_no = '" + shiftNumber + "' AND
pay_mode ilike '"+rset.getString(1) +"'");
while (rsetShifts.next()) {
java.sql.ResultSet rset2 = pstmt.executeQuery("select debit from ac_cash_book where
shift_no='"+shiftNumber+"'");
while (rset2.next()){
double debit =rset2.getDouble("debit");
if((rset2.getDouble("debit")<=0 ))
status = "no_banked";
else if((rset2.getDouble("debit")==rsetShifts.getDouble("amount")) &&
(rsetShifts.getDouble("amount"))< rsetShifts.getDouble("shift_amount"))
status= "BntClosed";
else if (rset2.getDouble(1)==rsetShifts.getDouble("shift_amount"))
Status ="bClosed";
shiftsVector.addElement(rset.getString(1)+":"+rsetShifts.getString(1)+":"+status);
}
}
}

java.sql.ResultSet rset = pstmt.executeQuery("SELECT DISTINCT payment_mode, transaction_type, credit FROM ac_cash_collection WHERE shift_no = '" + shiftNumber + "'");
java.sql.ResultSet rset2 = pstmt.executeQuery("select debit from ac_cash_book where shift_no='"+shiftNumber+"'");
Your second call releases the resources generated by the first one, that's why the ResultSet is closed.

Related

Java derby database not working

Is there any issue with these lines of code? All I get is "invalid entry".
I have a database called production with a table called PRODUCTION.
try {
String mk = jTextField1.getText();
String mn = jTextField2.getText();
String ab = (String) jComboBox1.getSelectedItem();
String bc = (String) jComboBox2.getSelectedItem();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:1527/production");
{
String host = "jdbc:mysql://localhost:1527/production";
JOptionPane.showMessageDialog(this, "connection success");
Statement stmt = con.createStatement();
String query = "update PRODUCT set FACTORY='" + ab + "' PRODUCT_NAME = '" + mk + "' UNIT= '" + bc + "' and OPENING_BALANCE'" + mn + "');";
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(this, "Record has been inserted");
stmt.close();
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "invalid entry");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error in Connectivity", "Message", 2);
}
Your query is not correct :
You have to use , between the fields
You don't need to use and when you set the fields (and OPENING_BALANCE'" + mn + "')
In the end of your query there are a closed parenthesis ) that you don't need it
But your way is open to sytax error and SQL Inection you have to use PreparedStatement instead, it is more secure and more helpful :
query = "update PRODUCT set FACTORY = ?, PRODUCT_NAME = ?, UNIT= ?, OPENING_BALANCE = ?";
try (PreparedStatement update = connection.prepareStatement(query)) {
update.setString(1, ab);
update.setString(2, mk);
update.setString(3, bc);
update.setString(4, mn);
update.executeUpdate();
}

How to create a table in access database using java

i need to create a table in access database. For this i tried with the following code
public class Testac {
public static void main(String[] args) {
try {
System.out.println("Begining conn");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String accessFileName = "Centre";
String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
Connection con = DriverManager.getConnection(connURL, "", "");
Statement stmt = con.createStatement();
System.out.println("Conn done succesfully");
stmt.execute("create table student ( Name string, ID integer )"); // create a student
stmt.execute("insert into student values(‘Md. SHAHJALAL’, ‘02223540’)"); // insert data into student
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Resultt that came from our query
if (rs != null) {
while (rs.next()) {
System.out.println("Name: " + rs.getString("Name") + " ID: " + rs.getString("ID"));
}
}
stmt.close();
con.close();
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}
But it throws the following error " ERROR: java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified ".
It is possible with UCanAccess
con = ConnectMdb(homedirectory+"/"+"Centre.accdb");
if (con != null) {
Statement st3 = null;
try {
st3 = (Statement) con.createStatement();
} catch (SQLException ex) {
Logger.getLogger(DataEntryScreen.class.getName()).log(Level.SEVERE, null, ex);
}
String sqlq3 = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
// System.out.println(sqlq1);
// ResultSet rs3 = null;
try {
st3.execute(sqlq3);
} catch (SQLException ex) {
Logger.getLogger(DataEntryScreen.class.getName()).log(Level.SEVERE, null, ex);
}
Try this.
Below Corrected Code may help you:
mistake in connection string and while creating table. need to use executeUpdate method
public class Testac {
public static void main(String[] args) {
try {
System.out.println("Begining conn");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String accessFileName = "Centre";
String connURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + accessFileName + ".accdb;PWD=";
Connection con = DriverManager.getConnection(connURL, "", "");
Statement stmt = con.createStatement();
System.out.println("Conn done succesfully");
stmt.executeUpdate("create table student ( Name string, ID integer )"); // create a student
stmt.execute("insert into student values(‘Md. SHAHJALAL’, ‘02223540’)"); // insert data into student
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Resultt that came from our query
if (rs != null) {
while (rs.next()) {
System.out.println("Name: " + rs.getString("Name") + " ID: " + rs.getString("ID"));
}
}
stmt.close();
con.close();
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}
The problem is on this line:
String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
which you should change to:
String connURL = "jdbc:odbc:DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
i.e. you need to remove the semi-colon between jdbc and odbc.

Show table names in MySQL database and the count of their records

I'm working on the next step of the class assignment and I want to do a query where I pull the metadata from the database to list the tables in it then include the count of records in the tables. I have it where it kind of works but in the first half shown it only puts a number 1 where the count of records should go. In the second half (I'm doing this for testing purposes now and will only have the first half if I can get it to work) it prints out the number of records just fine but I have the table name hard coded in. I want it to be able to read in the table name from the metadata result then execute the query for the count of records. I am running this in netbeans with a MySQL database and am using the JDBC driver.
connect();
try
{
String db = conn.getCatalog();
data.append("The current database " + db + " contains the following tables:\r\n");
}
catch(Exception err)
{
System.out.print(err + "\r\n");
}
try
{
ResultSet rs = null;
DatabaseMetaData md = conn.getMetaData();
rs = md.getTables(null, null, "%", null);
while (rs.next())
{
String tbl = rs.getString(3);
System.out.print(tbl + "\r\n");
ResultSet ct = null;
ct = conn.createStatement().executeQuery("SELECT COUNT(*) FROM" + tbl);
while (ct.next())
{
System.out.print(ct.getString(1) + "\r\n");
data.append("Table \"" + rs.getString(3) + "\" contains " + ct.getString(1) + " records.\r\n");
}
}
data.append("\r\n");
}
catch(Exception err)
{
System.out.print(err + "\r\n");
}
try
{
ResultSet ct = null;
ct = conn.createStatement().executeQuery("SELECT COUNT(*) FROM customer");
while (ct.next())
{
data.append(ct.getString(1) + "\r\n");
}
ResultSet pt = null;
pt = conn.createStatement().executeQuery("SELECT COUNT(*) FROM product");
while (pt.next())
{
data.append(pt.getString(1) + "\r\n");
}
}
catch(Exception err)
{
System.out.print(err + "\r\n");
}
With following query you can query all tables with number of rows, date size, index size etc on a specific database.
SELECT concat(table_schema,'.',table_name) tables,
concat(round(table_rows),'') rows,
concat(round(data_length/(1024),2),'') data_size,
concat(round(index_length/(1024),2),'') index_size,
concat(round((data_length+index_length)/(1024),2),'') total_size,
round(index_length/data_length,2) index_data_ratio
FROM information_schema.TABLES
WHERE table_schema like "%YOUR-DATABASE-NAME-HERE%"
ORDER BY rows DESC LIMIT 20;
This is what I ended up doing and it works exactly as I wanted. I ended up using a prepared statement in the while loop to make it work.
connect();
try
{
String db = conn.getCatalog();
data.append("The current database " + db + " contains the following tables:\r\n");
}
catch(Exception err)
{
System.out.print(err + "\r\n");
}
try
{
ResultSet rs = null;
DatabaseMetaData md = conn.getMetaData();
rs = md.getTables(null, null, "%", null);
while (rs.next())
{
String tbl = rs.getString(3);
String query = ("SELECT COUNT(*) FROM " + tbl);
PreparedStatement cnt = conn.prepareStatement(query);
ResultSet ct = cnt.executeQuery();
while (ct.next())
{
data.append("Table " + rs.getString(3) + " has " + ct.getString(1) + " records\r\n");
}
}
data.append("\r\n");
}
catch(Exception err)
{
System.out.print(err + "\r\n");
}

send a broadcast message to all items in list in java

I would like to send a broadcast message to all numbers returned from the select statement. It saves elements in the list but then it sends the same message to everyone. What am I doing wrong? Please see my method below.
public static List<Message> listAllMessages(Connection connection) {
List<Message> msg = new ArrayList<Message>();
String messages = ReturnTexts.getMessage(connection, "EMPTYMESSAGE");
String sql = "SELECT b.`productid` as productid, p.`productname` as productname, b.`msisdn` as msisdn , MAX(b.`amount`) as amount, b.`productcode` as productcode, a.`endDate` as enddate FROM "
+ TableNames.SAVEDBIDSTABLE
+ "b LEFT JOIN "
+ TableNames.PRODUCTTABLE1
+ " p ON b.`productcode`= p.`code` "
+ " JOIN "
+ TableNames.AUCTIONTABLE1
+ " a"
+ " ON b.`productcode`= a.`productcode` "
+ "GROUP BY msisdn, productcode ";
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
if (connection == null || connection.isClosed() )
connection = DBConnection.getConnection();
// LOGGER.info(sql);
statement = DBConnection.isConnected(connection).prepareStatement(
sql);
// statement = connection.createStatement();
resultSet = statement.executeQuery();
long productid = 0;
String productname = null;
String msisdn = null;
int amount = 0;
String productcode = null;
Date enddate = null;
while (resultSet.next()) {
productid = resultSet.getLong("productid");
productname = resultSet.getString("productname");
msisdn = resultSet.getString("msisdn");
amount = resultSet.getInt("amount");
productcode = resultSet.getString("productcode");
enddate = resultSet.getTimestamp("enddate");
msg.add(new Message(Long.valueOf(productid), productname,
msisdn, amount, productcode, String.valueOf(enddate)));
}
String messages = ReturnTexts
.getMessage(connection, "BROADCAST")
.replace("XXXX", productname)
// .replace("YYYY", String.valueOf(amount))
.replace("YYYY",
String.valueOf(maxBid(productcode, connection)))
.replace("ZZZZ", String.valueOf(enddate));
//LOGGER.info(messages.toString());
try {
for (Message obj : msg) {
obj.setMessage(messages);
String apiUrl = "url/sendsms.jsp";
getResponse(apiUrl + "?" + "user="
+ URLEncoder.encode("xxx", "UTF-8")
+ "&password="
+ URLEncoder.encode("xxx", "UTF-8")
+ "&mobiles=" + obj.getMsisdn() + "&sms="
+ URLEncoder.encode(obj.getMessage(), "UTF-8"));
//bulkMessagesLog(obj.getMsisdn(), obj.getMessage(),obj.getProductcode(), connection);
bulkMessagesLog(productcode, msisdn, productname, connection);
//LOGGER.info(obj.getMsisdn() + " : " + obj.getProductcode()+ " : " + obj.getMessage());
}
} catch (UnsupportedEncodingException e) {
System.err
.println("UnsupportedEncodingException while trying to send SMS.");
e.getMessage();
}
} catch (SQLException e) {
LOGGER.error(e.getMessage());
} finally {
DBConnection.closeAllDBUsage(resultSet, statement, null);
}
return msg;
}
public static void bulkMessagesLog(String msisdn, String message,String productcode,
Connection connection) {
PreparedStatement statement = null;
String sql = "INSERT INTO " + TableNames.BULK_MESSAGESLOGTABLE
+ "(`msisdn`,`message`,`productcode`,`dateCreated`) VALUES(?,?,?,now()) ";
try {
if ( connection == null || connection.isClosed() )
connection = DBConnection.getConnection();
statement = DBConnection.isConnected(connection).prepareStatement(
sql);
statement.setString(1, msisdn);
statement.setString(2, message);
statement.setString(3, productcode);
//statement.addBatch();
statement.executeUpdate();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
} finally {
DBConnection.closeAllDBUsage(null, statement, connection);
}
}
You do iterate over the result set and build a list of messages in msg. Though you only create the text once, outside of the loop, so it's always the same with the (last) productname etc.
Should probably also be created in the loop.

no results were returned by the query

Connection con = null;
Statement stmt = null;
Statement resultStmt = null;
ResultSet rs = null;
try {
// load database driver driver
System.out.println("Database driver is: " + DataSource.getClassName());
Class.forName(DataSource.getClassName());
// connect to database from a given URL with a given username and password
System.out.println("Database URL is: " + DataSource.getURL());
con = DriverManager.getConnection(DataSource.getURL(), DataSource.getUserName(), DataSource.getPassword());
// create an SQL statement object
stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO leadcustomer " + "VALUES(1, 'junwei', 'Li', 'heaven road','test#test.com')");
String SQLStatement = "SELECT * FROM leadcustomer";
System.out.println("Q1 SQL Statement is: " + SQLStatement);
rs = resultStmt.executeQuery(SQLStatement);
while (rs.next()) {
int customerid = rs.getInt("customerid");
String fistname = rs.getString("firstname");
String surname = rs.getString("surname");
String billAddress = rs.getString("billingAddress");
String email = rs.getString("email");
System.out.println("customerid : " + customerid);
System.out.println("firstname : " + fistname);
System.out.println("surname : " + surname);
System.out.println("billingAddress : " + billAddress);
System.out.println("email : " + email);
System.out.println(customerid + " : " + fistname + "--" + surname + "--" + billAddress + ":" + email);
}
con.close();
// extract name from first row and print
} catch (SQLException e) {
// print details of SQL error
// could be multiple errors chained together
System.err.println("Error(s) occurred");
while (e != null) {
System.err.println("SQLException : " + e.getMessage());
System.err.println("SQLState : " + e.getSQLState());
System.err.println("SQLCode : " + e.getErrorCode());
e = e.getNextException();
System.err.println();
}
}
I'm trying to insert data and select the table after inserted. But it returns the error message "no results were returned by the query"
I did use executeUpdate and executeQuery for different SQL statement.
Any suggestion for that?
BTW, the insert action is running successful.
The only thing I want is just to solve out the error and execute the select statement print out the table..
Your resultStmt hasn't been initialized. Add
resultStmt = con.createStatement();
before
rs = resultStmt.executeQuery(SQLStatement);

Categories