Database is locked in SQLite [Java] - java

updated
try
{
sqlite.setDbPath(dbPath);
con = sqlite.connect();
if(!con.isClosed())
{
String query="SELECT Username,Password FROM Apps WHERE Username ='"+username+"'"; // and Password='"+password+"'";
ResultSet rs = con.createStatement().executeQuery(query);
while(rs.next())
{
if(rs.getString("Username").equals(username))//confronto se Username รจ gia esistente
{
trovato = true;
risultato = "gia' presente";
}
}
if(trovato==false) {
createUsers(username,password,name,surname,email,appname,ip,authorized,token);
risultato="inserito";
}
if(con!=null)
{
con.close();
}
if(sqlite != null)
{
sqlite.close();
}
if(rs != null)
{
rs.close();
}
}
In try catch block I've open connection with database embedded but in first time i don't close all connection..
With if control the program close all open connection and works well

Update 2
Here is an abbreviated version using try-with-resource instead. Code is simpler and shorter
public String RegisterUser(... ) {
boolean trovato = false;
int authorized=0;
SqliteConnection sqlite = new SqliteConnection();
String dbPath="C:/Users/l.pellegrini/eclipse-workspace/ClayAPI_dbembedded/claydb.db";
String query="SELECT Username,Password FROM Apps WHERE Username ='"+username+"' and Password='"+password+"'";
try (java.sql.Connection con = sqlite.connect();
Statement statement = con.createStatement();
Statement updStatement = con.createStatement();
) {
ResultSet rsActiveServices = con.createStatement().executeQuery(query);
// handle result set as before
} catch(SQLException e) {
e.printStackTrace();
System.out.println("errore" + e);
}
if(trovato==false) {
createUser(username, password, name, surname, appname, email, ip)
}
return "username: " + username;
}
private createUser(String username, String password, String name, String surname, String appname, String email, String ip {
String query1="INSERT INTO Apps (Username,Password,Name,Surname,Email,AppName,Ip,Authorized,Token) VALUES ('" + username + "'," + "'" +password +"','" + name + "','" + surname + "','" +email + "','" + appname + "','"+ip+"','"+authorized+"','"+token+"')";
SqliteConnection sqlite = new SqliteConnection();
String dbPath="C:/Users/l.pellegrini/eclipse-workspace/ClayAPI_dbembedded/claydb.db";
try (java.sql.Connection con = sqlite.connect();
Statement statement = con.createStatement();) {
updStatement.executeUpdate(query1);
} catch(SQLException e) {
e.printStackTrace();
System.out.println("errore" + e);
}
}
It could very well be that your prepared statement isn't properly closed. Change
ResultSet rsActiveServices = con.createStatement().executeQuery(query);
to
statement = con.createStatement();
ResultSet rsActiveServices = statement.executeQuery(query);
where statement is declared before try
java.sql.Connection con = null;
Statement statement = null;
and then close it in your finally clause
finally
{
try
{
statement.close();
con.close();
sqlite.close();
}
Update 1
I just noticed that your are trying to close your objects twice which is wrong, remove the first set of close calls and only close within finally {} at the end.

Resolved
I do errors with open and close connection in Main.. With SQLite the connection you have to open and close everytime it's carried out a query of all type(Insert, Delete,Update ecc..)

Related

java.sql.SQLExecption:parameter index out of range (1>number of prameters, which is 0) for update sql

i have problem with my project, and it still new for me with MYSQL, i want to get data from database and do some calculation and update the value on it,
its like making withdraw function like ATM machine. This my table look like.
enter image description here . You can see constructor parameter that carry value (String value and String ID). For Value="100"; and ID="5221311" you can see it on my table picture.
public ConformWithdraw() {
initComponents();
try {
Class.forName("com.jdbc.mysql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:/atm", "root", "");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public ConformWithdraw(String value,String ID) {
initComponents();
this.value=value;
this.ID=ID;
}
------------------------------------------------------------
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
String validate = "SELECT * FROM customer_details WHERE accountID LIKE '" + ID
+ "'";
PreparedStatement smtm = con.prepareStatement(validate);
ResultSet resultSet = smtm.executeQuery();
User user = null;
if (resultSet.next()) {
user = new User();
user.setBalance(resultSet.getString("accountBalance"));
double balance=Double.parseDouble(user.getBalance());
double val=Double.parseDouble(value);
total =(balance - val);
}
smtm.close();
resultSet.close();
program();
} catch (SQLException | HeadlessException | ClassCastException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
-------------------------------------------------------------
public void program(){
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = '"+String.valueOf(total)+"'"
+ "WHERE accountID = '"+ID+"'";
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
PreparedStatement pstmt = con.prepareStatement(sqlUpdate);
id=Integer.parseInt(ID);
pstmt.setString(1, String.valueOf(total));
pstmt.setInt(2, id);
int rowAffected = pstmt.executeUpdate();
pstmt.close();
new ShowWithdraw().setVisible(true);
dispose();
}catch(SQLException | HeadlessException | ClassCastException ex){
JOptionPane.showMessageDialog(null, ex);
JOptionPane.showMessageDialog(null, "slh sini");
}
}
You are already setting the parameters on the query, so It tries to set the parameters and find no parameters to find. Try this:
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = ?"
+ "WHERE accountID = ?";

ORA-02289: sequence does not exist, cannot find my error

public static void main(String[] argv) {
try {
createTable();
insertRecordIntoTable("leo","123");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private static void createTable() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String sequence = "CREATE SEQUENCE ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999 MINVALUE 1 CACHE 20";
String createTableSQL = "CREATE TABLE DBUSER1("
+ "USER_ID NUMBER(5) NOT NULL, "
+ "USERNAME VARCHAR(20) NOT NULL, "
+ "PASSWORD VARCHAR(20) NOT NULL, "
+ "PRIMARY KEY (USER_ID) "
+ ")";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(createTableSQL);
System.out.println(createTableSQL);
// execute create SQL stetement
preparedStatement.executeUpdate(createTableSQL);
preparedStatement.executeUpdate(sequence);
System.out.println("Table \"dbuser\" is created!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER,DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
private static void insertRecordIntoTable(String username, String password) throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String insertTableSQL = "INSERT INTO DBUSER1"
+ "(USER_ID, USERNAME, PASSWORD) VALUES"
+ "(ID_SEQ.NEXTVAL,?,?)";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(insertTableSQL);
// execute insert SQL stetement
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
preparedStatement.executeUpdate();
System.out.println("Record is inserted into DBUSER table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
I cannot find the error when I try to create a sequence for my table.
When I try to insert some data in my table with the sequence it says it doesn't exist, but I did create it. Also I am not sure if i need a preparedStatement.setInt(1, seq_id.nextval); it gives an error but im not quite sure how I would do this
The solution might be adding the schema name (owner) before the name of sequence:
CREATE SEQUENCE some_nameOf_schema.ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999 MINVALUE 1 CACHE 20
You're preparing a statement with one SQL text, and executing the statement with two different SQL texts;
preparedStatement = dbConnection.prepareStatement(createTableSQL);
preparedStatement.executeUpdate(createTableSQL);
preparedStatement.executeUpdate(sequence);
...which is actually invalid according to the docs;
int executeUpdate(String sql)
throws SQLException
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
Note:This method cannot be called on a PreparedStatement or CallableStatement.
What you need to do is to prepare and execute two different statements;
preparedStatement = dbConnection.prepareStatement(createTableSQL);
preparedStatement.executeUpdate();
preparedStatement = dbConnection.prepareStatement(sequence);
preparedStatement.executeUpdate();
In general, it doesn't make much sense to CREATE database objects every time your application starts up, because this is something that's usually done only once, when you install/upgrade the database/schema the application uses.
However, if you really have to do it this way, the current solution could be improved so that the following points are considered:
Only execute the CREATE statements when the objects do not yet exist in the DB. This can be done by first inspecting the USER_OBJECTS data dictionary view.
Use a plain Statement instead of PreparedStatement for executing the DDL (prepared statements are only useful for DML operations that use input variables)
Handle JDBC resources (Connection / Statement / ResultSet) concisely and safely through the try-with-resources construct
Here's how the code could look like:
// query constants
private static final String CHECK_DB_OBJECT =
"SELECT 1 FROM user_objects WHERE object_name = ?";
private static final String CREATE_SEQUENCE =
"CREATE SEQUENCE ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999" +
" MINVALUE 1 CACHE 20";
private static final String CREATE_TABLE = "CREATE TABLE DBUSER1("
+ "USER_ID NUMBER(5) NOT NULL, "
+ "USERNAME VARCHAR(20) NOT NULL, "
+ "PASSWORD VARCHAR(20) NOT NULL, "
+ "PRIMARY KEY (USER_ID) "
+ ")";
/* clip the main method etc. */
/**
* Creates the table and sequence only if they do not already exist.
*/
private static void createTableAndSequenceIfAbsent() {
try (Connection dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER, DB_PASSWORD);
PreparedStatement ps = dbConnection
.prepareStatement(CHECK_DB_OBJECT)) {
if (!dbObjectExists(ps, "ID_SEQ")) {
executeDDL(dbConnection, CREATE_SEQUENCE);
}
if (!dbObjectExists(ps, "DBUSER1")) {
executeDDL(dbConnection, CREATE_TABLE);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static boolean dbObjectExists(PreparedStatement ps,
String objectName) throws SQLException {
ps.setString(1, objectName);
ResultSet rs = ps.executeQuery();
// if the #CHECK_DB_OBJECT query returned a row, the object exists
return rs.next();
}
private static void executeDDL(Connection c, String sql)
throws SQLException {
try (Statement st = c.createStatement()) {
st.execute(sql);
}
}

Connect to MySQL on Android, Driver doesn't work

I want to connect to my MySQL server, but the driver doesn't work.
How can I fix this, or what am I doing wrong? Do I need to import extra libraries (I didn't do that)?
This is my code:
public void Connection() {
String retrievedUserName = "";
String retrievedPassword = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://domainexample.com", "username", "passwoord");
PreparedStatement statement = con.prepareStatement("SELECT * FROM Gebruiker WHERE users= '" + "username" + "'");
ResultSet result = statement.executeQuery();
while (result.next()) {
retrievedUserName = result.getString("gebruikersnaam");
retrievedPassword = result.getString("password");
}
System.out.println(retrievedUserName + " passwoord = " + retrievedPassword);
} catch (Exception e) {
e.printStackTrace();
}
}

JAVA JDBC SQL updating a new database based on the old database records

I am trying to write a runnable jar file that can be able to connect to 2 different databases informix old database and oracle new database. It should be able to update the new database(oracle) with the old database(informix) records.
I re-edit my java code I added separate methods for my select, update and connections I am not getting an error but its not updating my db. My select works but my update statement is not working. This is my result i get - SELECT profile_id, ingress_flag, egress_flag, ce_ingress_flag, ce_egress_flag from COS_PROFILE where profile_id = 102
profileid : 102
ingressflag : Y
egress_flag : Y
ceingressflag : Y
ceegressflag : Y
ResultSet not open, operation 'next' not permitted. Verify that autocommit is OFF
I am not sure how can I fixed the ResultSet not open, operation 'next' not permitted. Verify that autocommit is OFF
public class TestConnection {
static ResultSet rs;
public static void main (String[] args) throws Exception {
try{
selectRecordsIcore();
updateRecordIntoBids();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void selectRecordsIcore() throws SQLException {
Connection dbConnection = null;
Statement statement = null;
String selectTableSQL = "SELECT profile_id, ingress_flag, egress_flag, ce_ingress_flag, ce_egress_flag from COS_PROFILE";
try {
dbConnection = getInformixConnection();
statement = dbConnection.createStatement();
System.out.println(selectTableSQL);
// execute select SQL stetement
rs = statement.executeQuery(selectTableSQL);
while (rs.next()) {
int profileid = rs.getInt("profile_id");
String ingressflag = rs.getString("ingress_flag");
String egress_flag = rs.getString("egress_flag");
String ceingressflag = rs.getString("ce_ingress_flag");
String ceegressflag = rs.getString("ce_egress_flag");
System.out.println("profileid : " + profileid);
System.out.println("ingressflag : " + ingressflag);
System.out.println("egress_flag : " + egress_flag);
System.out.println("ceingressflag : " + ceingressflag);
System.out.println("ceegressflag : " + ceegressflag);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
private static void updateRecordIntoBids() throws SQLException {
Connection dbConnection = null;
Statement statement = null;
ArrayList<TempStorageRecords> updateSQL = new ArrayList<TempStorageRecords>();
while (rs.next()) {
int profileid = rs.getInt("profile_id");
String ingressflag = rs.getString("ingress_flag");
String egress_flag = rs.getString("egress_flag");
String ceingressflag = rs.getString("ce_ingress_flag");
String ceegressflag = rs.getString("ce_egress_flag");
String updateTableSQL = "UPDATE traffic_profile SET ingress_flag = " + ingressflag
+ " ,egress_flag = " + egress_flag
+ " ,ce_ingress_flag = " + ceingressflag
+ " ,ce_egress_flag = " + ceegressflag
+ " WHERE profile_id = " + profileid + ";";
try {
dbConnection = getOracleConnection();
statement = dbConnection.createStatement();
System.out.println("updateTableSQL 1 :" + updateTableSQL);
// execute update SQL stetement
statement.execute(updateTableSQL);
System.out.println("updateTableSQL 2: " + updateTableSQL);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
}
public static Connection getOracleConnection() throws SQLException {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#oracle_host:1521:BIDS";
String username = "username";
String password = "password";
try {
Class.forName(driver);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // load Oracle driver
Connection dbConnection = null;
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
url, username,password);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
public static Connection getInformixConnection() throws SQLException {
String driver = "com.informix.jdbc.IfxDriver";
String url = "jdbc:informix-sqli://informix_host:1615/icore:INFORMIXSERVER=icit";
String username = "user";
String password = "pass";
try {
Class.forName(driver);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // load Informix driver
Connection dbConnection = null;
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
url, username,password);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
}
At first try to export data from source database into text file.
Your code uses hard coded column names, but I think it could read table names to export from some config file and column names from metadata from SELECT * FROM [table_name]. In JDBC there is getMetaData() for RecordSet. Use it.
When you export data into text files without problems you can do the next step: import such data directly from the source database to the destination database.
For destination database create prepareStatement with:
'INSERT INTO ' + table_name_dest + ' (' + column_names +') VALUES ('+ question_marks + ')'
(there question_marks are '?' chars which maps to columns).
Then for each record from source table and for each record (row) do:
insert_stmt.setObject(i, rs_in.getObject(i))
For big tables you can also use setFetchSize() and addBatch()/executeBatch()

JDBC oracle update statements in java

Can someone tell me why this fails at the ps.excuteUpdate statement? It seems to work and changes the data in the database but it fails at the execute statement which won't let it execute the other two ps1 and ps2 statements.
buyStock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
BuyStock();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
public void BuyStock() throws SQLException, IOException{
Connection conn = null;
PreparedStatement ps = null;
PreparedStatement ps1 = null;
PreparedStatement ps2 = null;
int i = 0;
String username = UserLoginInfo.userEmail;
int bank = 75000;
String string1= "goog";
int shares = 25;
conn = ConnectionManager.getConnection();
if (i == 0) {
ps = conn.prepareStatement("UPDATE L1_Standings SET BANK = ? WHERE EMAIL = '" + username + "'");
ps1 = conn.prepareStatement("UPDATE L1_Stocks SET TICKER_SYMBOL = ? WHERE EMAIL = '" + username + "'");
ps2 = conn.prepareStatement("UPDATE L1_Stocks SET NUM_SHARES = ? WHERE EMAIL = '" + username + "'");
ps.setInt(1, bank);
ps1.setString(1, string1);
ps2.setInt(1, shares);
ps.executeUpdate();
ps1.executeUpdate();
ps2.executeUpdate();
ps.close();
ps1.close();
ps2.close();
} else {
System.out.println("False");
}

Categories