Whenever I try to close the resources rs.close() or stmt.close() or even conn.close() I get an error saying "unreachable statement". Strange thing is that it works in other methods. Maybe I forgot something?
public static boolean exists(int av) {
try {
Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
Statement stmt = conn.createStatement();
String query = "SELECT id FROM audiovisuals WHERE id='" + av + "' LIMIT 1";
ResultSet rs = stmt.executeQuery(query);
if(!rs.isBeforeFirst()) {
return false;
}
else {
return true;
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
String error = "SQLException: " + e.getMessage() + "\nSQLState: " + e.getSQLState() + "\nVendorError: " + e.getErrorCode();
return false;
}
}
I'm assuming here that you are getting unreachable statement because you are putting the calls after a return statement. You need to put the close calls in a finally block. So your method would look something like this:
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
stmt = conn.createStatement();
String query = "SELECT id FROM audiovisuals WHERE id='" + av + "' LIMIT 1";
rs = stmt.executeQuery(query);
if(!rs.isBeforeFirst()) {
return false;
}
else {
return true;
}
} catch (SQLException e) {
String error = "SQLException: " + e.getMessage() + "\nSQLState: " + e.getSQLState() + "\nVendorError: " + e.getErrorCode();
return false;
} finally {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
}
This looks like a good place to use try-with-resources. With you code, it would look like this
public static boolean exists(int av) {
try(Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id FROM audiovisuals WHERE id='" + av + "' LIMIT 1")){
if(!rs.isBeforeFirst()) {
return false;
}
else {
return true;
}
} catch (SQLException e) {
String error = "SQLException: " + e.getMessage() + "\nSQLState: " + e.getSQLState() + "\nVendorError: " + e.getErrorCode();
return false;
}
}
Your close statements can never be reached, since you return before in both if cases.
You can use try-with-resources to close AutoCloseables automatically (everything you try to close is autocloseable):
try {
String query = "SELECT id FROM audiovisuals WHERE id='" + av + "' LIMIT 1";
try (Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
if(!rs.isBeforeFirst()) {
return false;
}
else {
return true;
}
} // resources are automatically closed here
} catch (SQLException e) {
String error = "SQLException: " + e.getMessage() + "\nSQLState: " + e.getSQLState() + "\nVendorError: " + e.getErrorCode();
}
return false;
Try-with-resources closes all resources (conn, stmt amd rs) even if an exception is thrown for one of the close() method calls.
Related
I am getting the following error when i try to execute my query(s),but i don't know why it gives me the following error every time i try to execute my query(s).The error also appears in my logcat and not in a toast as i expected.
here is my code!!
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
runOnUiThread(new Runnable() {
public void run() {
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy/mm/dd");
String formattedDate = df.format(c);
System.out.println("it isssssssssssssssssssssssssssssssssssssssssaaaaaaaaaaaaaaaaaaaa"+getIntent().getStringExtra("nameid"));
String query = "Insert into CustomerSupportChat values('" + formattedDate + "','" + themsg.getText().toString() + "','Customer','3','"+getIntent().getStringExtra("nameid")+"','1','1') " +
"Select MessageID,MessageDate,MessageText,SenderType,MessageRecieved,MessageReaded,Users_Login_Data.Username,StoresData.StoreEnglishName,StoresData.StoreArabicName FROM " +
"CustomerSupportChat INNER JOIN Users_Login_Data ON " +
"CustomerSupportChat.CustomerID = Users_Login_Data.CustomerID INNER JOIN StoresData ON " +
"CustomerSupportChat.StoreID = StoresData.StoreID";
String query2 =
"Select MessageID,MessageDate,MessageText,SenderType,MessageRecieved,MessageReaded,Users_Login_Data.Username,StoresData.StoreEnglishName,StoresData.StoreArabicName FROM " +
"CustomerSupportChat INNER JOIN Users_Login_Data ON " +
"CustomerSupportChat.CustomerID = Users_Login_Data.CustomerID INNER JOIN StoresData ON " +
"CustomerSupportChat.StoreID = StoresData.StoreID Where SenderType = 'Store'";
Statement stmt = conn.createStatement();
Statement stmt2 = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSet rs2 = stmt2.executeQuery(query2);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListChat(rs.getString("MessageDate"), rs.getString("MessageText"), rs.getString("SenderType"), rs2.getString("MessageText")));
themsg.setText("");
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
}
});
return msg;
}
I have tried removing while and replacing it with if statement but it showed me the same error.
I also tried my query on mssql and it executed successfully.
EDIT I solved it by changing the date format to MM/dd/yyyy.
But now i get the following error:
java.sql.SQLException: No current row in the ResultSet.
Any ideas?
Looks like there is no null check for rs2 in the below line so could throw that error:
itemArrayList.add(new ClassListChat(rs.getString("MessageDate"), rs.getString("MessageText"), rs.getString("SenderType"), rs2.getString("MessageText")));
Also a better way to check for ResultSet not returning anything is like this:
if (rs.next() == false){
msg = "No Data found!";
success = false;
} else {
do {
// add items to itemArraylist...
} while (rs.next());
}
Read more: https://javarevisited.blogspot.com/2016/10/how-to-check-if-resultset-is-empty-in-Java-JDBC.html#ixzz6KIFZZHNB
How do I tell my java program to retrieve the next matching record into my default table model.
Below is my home work so far.using jTable tb1 and default table model dtm is compulsory for me.
private void Show_My_LettersActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(url, "root", "root");
System.out.println("Connected database successfully...");
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT * from LCI where SUB_ID = '" + SUB_ID_.getText() + "' AND L_DATE = '" + DATE.getText() + "'";
ResultSet rs1, rs2, rs3, rs4, rs5, rs6, rs7;
rs1=j.getData("select COUNT(*) from LCI");
try (ResultSet rs = stmt.executeQuery(sql)) {
DefaultTableModel dtm = (DefaultTableModel) tb1.getModel();
while (rs.next()) {
String L_ID_ = rs.getString("L_ID");
String L_DATE_ = rs.getString("L_DATE");
String heading = rs.getString("HEADING");
String sub_id = rs.getString("SUB_ID");
System.out.print("ID: " + L_ID_);
System.out.print(", Letter date: " + L_DATE_);
System.out.print(", Heading " + heading);
System.out.println(", Subject ID " + sub_id);
/* This gives the correct out put when debug is done.
But the below code doesn't retrive the full out put.
It gives only the very first record matching with the user inputs*/
Vector v = new Vector();
Vector v1 = new Vector();
Vector v2 = new Vector();
Vector v3 = new Vector();
JOptionPane.showMessageDialog(this, "Done");
dtm.getColumnName(1);
v.addElement(rs.getString(1));
dtm.addColumn(v);
dtm.getColumnName(3);
v1.addElement(rs.getString(3));
dtm.addColumn(v1);
dtm.getColumnName(10);
v2.addElement(rs.getString(10));
dtm.addColumn(v2);
// stmt.executeQuery("SELECT * FROM LCI WHERE L_ID IN(SELECT (L_ID + 1)FROM LCI WHERE L_DATE = '"+DATE.getText()+"'");
dtm.addRow(v3);
//stmt.executeQuery("SELECT * FROM LCI WHERE L_ID IN(SELECT (L_ID '"+(+1)+"')FROM LCI WHERE L_DATE = '"+DATE.getText()+"'");
}
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}// TODO add your handling code here:
}
I have a sqlite db file created by other program, and checked everything is fine.
Then after doing select query to get some data, some of the row disappear after this process. I tried to use prepareStatement and though it worked but this remained.
my code
private ForecastTableItem selectItemPrepareStatement(String tableName, String columnName, String name) {
ForecastTableItem item = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + dbLocation);
System.out.println("Selecting item from tableName: "+tableName + " of col: "+columnName + " : "+name);
String query = "SELECT * FROM " + tableName + " WHERE " + columnName + "=? COLLATE NOCASE";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, name);
rs = pstmt.executeQuery();
if (rs.next()) {
if (tableName.equalsIgnoreCase("mainTable")) {
item = new ForecastTableItem();
item.setId(rs.getInt("Id"));
item.setTitle(rs.getString("title"));
item.setLink(rs.getString("link").toLowerCase());
item.setPositionType(rs.getString("positionType"));
item.setPackageName(rs.getString("packageName"));
item.setCsvFilePath(rs.getString("csvFilePath"));
item.setSubpackageName(rs.getString("subpackageName"));
item.setTimeFrame(rs.getString("timeFrame"));
item.setForecastDate(rs.getString("forecastDate"));
item.setTargetDate(rs.getString("targetDate"));
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
if(pstmt != null) try{ pstmt.close();} catch(SQLException e){};
if(rs != null) try{ rs.close();} catch(SQLException e){};
if(conn != null) try{ conn.close();} catch(SQLException e){};
}
return item;
}
after COLLATE NOCASE use semi-column
"SELECT * FROM " + tableName + " WHERE " + columnName + "= ? COLLATE NOCASE;";
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.
Hey guys I just got my first java job but if things go well I may never need to code again.
What I need to do is connect to a database and apply interest to a large number of transactions.
I am having trouble getting the math to work right on my local machine. This must be correct to within a fraction of a cent. Any ideas? Thanks in advance!
public Connection getConnection() throws SQLException {
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", "MY_USER");
connectionProps.put("password", "MY_PASSWORD");
if (this.dbms.equals("mysql")) {
conn = DriverManager.getConnection(
"jdbc:" + this.dbms + "://" +
"YR1F4K3QAS3RV3R" +
":" + this.portNumber + "/",
connectionProps);
} else if (this.dbms.equals("derby")) {
conn = DriverManager.getConnection(
"jdbc:" + this.dbms + ":" +
this.dbName +
";create=true",
connectionProps);
}
System.out.println("Connected to database");
return conn;
}
public static void ApplyInterestToHighVolumeAccounts(Connection con, String dbName, String InterestToApply)
throws SQLException {
Statement stmt = null;
String query = "select * "from " + dbName + ".HighVolumeAccounts";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String AccountName = rs.getString("AccountName");
int AccountNumber = rs.getInt("AccountNumber");
int Balance = rs.getInt("Balance");
int Interest = InterestToApply
int newBalance = Balance + (Balance * Interest) - (Balance * 0.00000001%)
int AddToRetirement = Balance * 0.000001%
String GetRich = "UPDATE TBL_Accounts SET Balance=Balance" + AddToRetirement + " WHERE AccountName=PrivateAccountInTheCaymens";
ResultSet rs = stmt.executeQuery(GetRich);
String AdjustBalance = "UPDATE TBL_Accounts SET Balance=Balance" + newBalance + " WHERE AccountName=AccountName";
ResultSet rs = stmt.executeQuery(AdjustBalance);
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}
I think you are really close. BigDecimals would be one way to go.
Use the following code verbatum and you should be fine:
import java.sql.*;
import java.math.BigDecimal;
import java.math.MathContext;
public class adjustaccounts{
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://YR1F4K3QAS3RV3R";
static final String USER = "MY_USER";
static final String PASS = "MY_PASSWORD";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM HighVolumeAccounts";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int accountnumber = rs.getInt("AccountNumber");
BigDecimal balance = rs.getBigDecimal("Balance");
String accountname = rs.getString("AccountName");
double pennyshave = 0.000000001;
BigDecimal difference = balance.multiply(new BigDecimal(pennyshave));
//Pad your account
sql = "UPDATE TBL_Accounts SET Balance=Balance +" + difference + " WHERE AccountNumber=00098793302999"; //don't worry about this number, its a Java thing
stmt.executeQuery(sql);
//Adjust the other one.
sql = "UPDATE TBL_Accounts SET Balance=Balance -" + difference + " WHERE AccountName="+ accountname;
stmt.executeQuery(sql);
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}