no results were returned by the query - java

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);

Related

Java [SQLITE_ERROR] SQL error or missing database (near "resi": syntax error)

i have some issues when i'm run the program. It says "[SQLITE_ERROR] SQL error or missing database (near "resi": syntax error)" and "ada yang salah:java.sql.SQLException: ResultSet is TYPE_FORWARD_ONLY". Am i passed something or what?
connection code
public void koneksiDatabase(){
try{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:C:/Users/sqlite3/cekresi.db","root","");
System.out.println("Koneksi berhasil!");
}catch(ClassNotFoundException eclass){
System.out.println("Koneksi Gagal!");
}catch(SQLException esql){
System.out.println(esql.getMessage());
}
}
savedata code
public void simpanData(){
try {
String sql = "Insert into data resi = \"" + txtResi.getText() + "\","
+ "nama = \"" + txtNama.getText() + "\","
+ "tujuan = \"" + (String)cmbTujuan.getSelectedItem() + "\","
+ "tarif = \"" + txtTarif.getText() + "\","
+ "berat = \"" + txtBerat.getText() + "\","
+ "jumlah = \"" + txtJumlah.getText() + "\"";
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
System.out.println("berhasil!");
}catch (Exception e){
System.out.println(e);
}
tampilDataKeTabel();
}
showtable code
public void tampilDataKeTabel(){
ResultSet rs = null;
try{
Statement stmt = con.createStatement();
rs = stmt.executeQuery("select * from data");
ResultSetMetaData meta = rs.getMetaData();
int col = meta.getColumnCount();
int baris = 0;
while (rs.next()){
baris = rs.getRow();
}
dataTable = new String[baris][col];
int x = 0;
rs.beforeFirst();
while(rs.next()){
dataTable[x][0] = rs.getString("resi");
dataTable[x][1] = rs.getString("nama");
dataTable[x][2] = rs.getString("tujuan");
dataTable[x][3] = rs.getString("tarif");
dataTable[x][4] = rs.getString("berat");
dataTable[x][5] = rs.getString("jumlah");
x++;
}
tabelDisplay.setModel(new DefaultTableModel(dataTable,header));
}catch(Exception e){
System.err.println("ada yang salah:"+e);
}
}
There are syntax issues in the insert statement. The syntax should be:
INSERT INTO table (column1,column2 ,..)
VALUES( value1, value2 ,...);
So your insert statement should be something like:
String sql = "Insert into data(resi,nama,tujuan,tarif,berat,jumlah)
values(\"" + txtResi.getText() + "\","
+ \"" + txtNama.getText() + "\","
+ \"" + (String)cmbTujuan.getSelectedItem() + "\","
+ \"" + txtTarif.getText() + "\","
+ \"" + txtBerat.getText() + "\","
+ \"" + txtJumlah.getText() + "\")";
Also, there is an issue in the code to show the data.
while (rs.next()){
baris = rs.getRow();
}
This loop is traversing the result set once. So the next loop would fail as rs has already reached the end of results.
This is causing the exception : ResultSet is TYPE_FORWARD_ONLY
Instead of creating a 2D string array, Create a class corresponding to your db table and then create a List. Assuming a class named Data would be created, the second while loop would be :
List<Data> dataList = new ArrayList<>();
while(rs.next()){
Data data = new Data();
data.setResi(rs.getString("resi"));
data.setNama(rs.getString("nama"));
data.setTujuan(rs.getString("tujuan"));
data.setTarif(rs.getString("tarif"));
data.setBerat(rs.getString("berat"));
data.setJumlah(rs.getString("jumlah"));
dataList.add(data);
}

How to update null cells of specific column with mode of that column ? (Sql using Java)

I used the following code to calculate mode of a column:
public void CalcCatValMean(String colName , String tableName){
Statement st = null;
String sql = null;
String mode = null;
try{
setConnection();
st = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
sql = "SELECT " + colName + " , Count(colName) AS Frequency FROM " + tableName + " GROUP BY " + colName + " HAVING Count(colName) >= ALL (SELECT Count(colName) FROM " + tableName + " GROUP BY " + colName + " )";
System.out.println("sql :" + sql);
ResultSet rset = st.executeQuery(sql);
CachedRowSet rowset = new CachedRowSetImpl();
rowset.populate(rset);
int i = 1;
while(rowset.next()) { // check if a result was returned
mode = rowset.getString(i); // get your result
System.out.println("mode is : " + mode);
i++;
}
//Clean-up environment
st.close();
closeConnection();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But the weird thing is that its' also calculating "null" as a value & giving output of following column as "null".
null
abc
null
null
xyz
What I want to do is to calculate mode of all values of that column except null and then update null cells of that column with calculated mode.

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");
}

SQLException: This ResultSet is closed

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.

Categories