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;";
Related
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:
}
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();
}
I am trying to map a particular character to show the full word so in this code below I have a translate method, a select method that is selecting from the remote database and update method that updates those column to my local database.
My remote database has a column called profile_ind this columns only has single chars B,C,F,P,S,W in the data, and once I do the update I want to be able to translate it to the full word only without the chars. B = BENIGN, C = CUSTOMER, F = FRAME, P = PPCOS, S = STANDARD, W = W-RED
And in my update method I want to call that translate method. cos_profile_type is the column on my local database that I want to update to either BENIGN, CUSTOMER, FRAME,PPCOS,STANDARD,W-RED depending on profile_ind column in the remote db. How can I implement it ? how can i call that translate method in the update method when I set the ? in that statement.
public static String translate(String indicator) throws Exception {
if (indicator == null || indicator.length() == 0) return "";
if (indicator.equals("B")) return "BENIGN";
if (indicator.equals("C")) return "CUSTOMER";
if (indicator.equals("F")) return "FRAME";
if (indicator.equals("P")) return "PPCOS";
if (indicator.equals("S")) return "STANDARD";
if (indicator.equals("W")) return "W-RED";
System.out.println(indicator);
return "";
}
public static void selectRecordsIcore() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
Statement statement = null;
java.util.Date date= new java.util.Date();
String selectTableSQL = "SELECT profile_id, ingress_flag, egress_flag, ce_ingress_flag, ce_egress_flag, profile_ind from COS_PROFILE"
+ " WHERE profile_id >= ? AND profile_id <= ? ;";
try {
dbConnection = getInformixConnection(); //connects to ICORE database
System.out.println("ICORE Select Statement: " + selectTableSQL);
//Gets the max profile_id record
statement = dbConnection.createStatement();
ResultSet r = statement.executeQuery("SELECT max(profile_id) AS rowcount FROM COS_PROFILE");
r.next();
int maxCount = r.getInt("rowcount");
System.out.println("COS_PROFILE table has " + maxCount + " row(s).");
preparedStatement = dbConnection.prepareStatement(selectTableSQL);
preparedStatement.setInt(1, 1);
preparedStatement.setInt(2, maxCount);
// execute select SQL statement
rs = preparedStatement.executeQuery();
updateRecordIntoBids();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("inside the finally block ICORE " + new Timestamp(date.getTime()));
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
System.out.println("ICORE Statement Connection is closed");
}
if (preparedStatement != null) {
preparedStatement.close();
System.out.println("ICORE PreparedStatement Connection is closed");
}
if (dbConnection != null) {
dbConnection.close();
System.out.println("Database ICORE Connection is closed");
}
}
}
private static void updateRecordIntoBids() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
Statement statement = null;
dbConnection = getOracleConnection(); //connects to BIDS database
java.util.Date date= new java.util.Date();
//Gets the max profile_id record
statement = dbConnection.createStatement();
dbConnection.setAutoCommit(false);
ResultSet r = statement.executeQuery("SELECT count (*) AS rowcount FROM traffic_profile_temp");
r.next();
int maxCount = r.getInt("rowcount");
System.out.println("Traffic_profile_temp table before update has " + maxCount + " row(s).");
String updateTableSQL =
"UPDATE traffic_profile_temp SET pe_ingress_flag = ?, "
+ " pe_egress_flag = ?,"
+ " ce_ingress_flag = ?,"
+ " ce_egress_flag = ?, "
+ " cos_profile_type = ? "
+ " WHERE traffic_profile_id = ? ";
// execute update SQL statement
System.out.println("BIDS Update Statement: " + updateTableSQL);
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
System.out.println("Updating Bids Database in process ...");
try {
int rowCount = 0;
int expectedId = 1;
int first = 0;
while (rs.next()) {
String ingressflag = rs.getString("ingress_flag"); //BIDS column is pe_ingress_flag
String egressflag = rs.getString("egress_flag"); //BIDS column is pe_egress_flag
String ceingressflag = rs.getString("ce_ingress_flag"); //BIDS column is ce_ingress_flag
String ceegressflag = rs.getString("ce_egress_flag"); //BIDS column is ce_egress_flag
String profileind = rs.getString("profile_ind"); //BIDS column is cos_profile_type
int profileid = rs.getInt("profile_id"); //BIDS column is traffic_profile_id
preparedStatement.setString(1, ingressflag);
preparedStatement.setString(2, egressflag);
preparedStatement.setString(3, ceingressflag);
preparedStatement.setString(4, ceegressflag);
preparedStatement.setString(5, profileind);
preparedStatement.setInt(6, profileid);
preparedStatement.addBatch();
rowCount++;
if(expectedId == profileid){
if(first == 0){
first = expectedId-1;
}
}
if(expectedId != profileid){
if(first > 0){
System.out.println ("Profile id "+first+" to "+(expectedId-1)+" update.");
first = 0;
}
System.out.println ("Profile id "+expectedId+" to "+(profileid-1)+" missing.");
expectedId = profileid;
}
expectedId++;
}
if(first > 0){
System.out.println("Profile id "+first+" to "+(expectedId-1)+" update.");
first = 0;
}
preparedStatement.executeBatch();
dbConnection.commit();
System.out.println("Record(s) Updated : " + rowCount + new Timestamp(date.getTime()));
} catch (SQLException e) {
System.out.println("Update records Failed!! " + e.getMessage());
} finally {
System.out.println("inside the finally block BIDS" + " timestamp " + new Timestamp(date.getTime()));
if (statement != null) {
statement.close();
System.out.println("BIDS Statement Connection is closed");
}
if (preparedStatement != null) {
preparedStatement.close();
System.out.println("BIDS PreparedStatement Connection is closed");
}
if (dbConnection != null) {
dbConnection.close();
System.out.println("Database BIDS Connection is closed");
}
}
}
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.
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.