I'm calling this method:
ArrayList<String> selectFilteredJump(String owner, String fromDate, String toDate, String env) {
ArrayList<String> a = new ArrayList<>();
Connection c;
Statement stmt;
StringBuilder whereClause = new StringBuilder("WHERE a.Date BETWEEN '"+fromDate+ "' and '" + toDate+"'");
if (!env.equals(constants.EMPTY) ) {
whereClause.append(" and a.Environment = '").append(env).append("'");
}
if (!owner.equals(constants.EMPTY) ) {
whereClause.append(" and a.UserId = '").append(owner).append("'");
}
String sql = "SELECT a.TicketID, a.Subject, a.UserID, a.Date, a.Solution, a.Comments," +
"a.Environment, (SELECT UserName FROM Users WHERE UserID = a.UserID) AS UserName FROM Tickets a " +
whereClause + " order by 4 asc;";
System.out.println(sql);
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:" + this.dbPath + this.dbName) ;
c.setAutoCommit(false);
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
a.add(rs.getString("TicketID"));
a.add(rs.getString("Subject"));
a.add(rs.getString("UserID"));
a.add(rs.getString("Date"));
a.add(rs.getString("Solution"));
a.add(rs.getString("Comments"));
a.add(rs.getString("Environment"));
a.add(rs.getString("UserName"));
}
rs.close();
stmt.close();
c.close();
}
catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return a;
}
Everything executes correctly but it seems that my database remains locked with no visible reason.
On the other side if I'm replacing with this method the database is ok after executing it:
ArrayList<String> selectAllJump() {
if (constants.DEBUG_MODE) System.out.println("selectAllJump");
ArrayList<String> a = new ArrayList<>();
Connection c;
Statement stmt;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:" + this.dbPath + this.dbName);
c.setAutoCommit(false);
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a.TicketID, a.Subject, a.UserID, a.Date, a.Solution, a.Comments," +
"a.Environment, (SELECT UserName FROM Users WHERE UserID = a.UserID) AS UserName FROM Tickets a " +
"order by 4 asc;");
while (rs.next()) {
a.add(rs.getString("TicketID"));
a.add(rs.getString("Subject"));
a.add(rs.getString("UserID"));
a.add(rs.getString("Date"));
a.add(rs.getString("Solution"));
a.add(rs.getString("Comments"));
a.add(rs.getString("Environment"));
a.add(rs.getString("UserName"));
}
rs.close();
stmt.close();
c.close();
}
catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return a;
}
I've also tried to open the connection using specific configuration (like this):
c = DriverManager.getConnection("jdbc:sqlite:" + this.dbPath + this.dbName,setConfig().toProperties()) ;
private SQLiteConfig setConfig() {
SQLiteConfig config = new SQLiteConfig();
config.enforceForeignKeys(true);
config.setTempStore(SQLiteConfig.TempStore.MEMORY);
config.setCacheSize(1000);
config.setReadOnly(true);
return config;
}
and still the same error:
org.sqlite.SQLiteException: [SQLITE_BUSY] The database file is locked (database is locked)
Any idea is welcomed.
Thank you.
Related
so I'm trying to hash some passwords from a database from a login form and when I try first time to login it works with the password from database then I hash it with MD5 then when I come back to the login page I want to put the previously used password to log me in but it changed to the MD5 one. Is there any solution to have the MD5 one in the database and me to login with the first used?Thanks in advance (smecher.j is a variable who is 0)
public void validateLogin(){
DatabaseConnection connectNow = new DatabaseConnection();
DatabaseConnection connectNow2 = new DatabaseConnection();
Connection connectDB = connectNow.getConnection();
Connection connectDB2 = connectNow2.getConnection();
String verifyLogin = " SELECT count(1) FROM user_account WHERE username = '" + usernameTextField.getText() + "' AND password ='" + enterPasswordField.getText() +"'";
String insertFields3 = " UPDATE user_account SET password = MD5(password) WHERE username = '" + usernameTextField.getText() +"'";
try{
Statement statement = connectDB.createStatement();
Statement statement2 = connectDB2.createStatement();
ResultSet queryResult = statement.executeQuery(verifyLogin);
while(queryResult.next()){
if(queryResult.getInt(1)==1){
login1();
if(smecher.j==0) {
statement2.executeUpdate(insertFields3);
smecher.j++;
}
text1=enterPasswordField.getText();
}else{
loginMessageLabel.setText("Invalid login, please try again");
}
}
lol();
}catch(Exception e){
e.printStackTrace();
e.getCause();
}
}
public static String text1 = "";
public void lol() {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String dbUrl = "jdbc:mysql://localhost:3306/databaselol?autoReconnect=true&useSSL=false";
String dbUsr = "root";
String dbPass = "!Iloriana12";
try {
String sql = "SELECT password FROM user_account where username = '" + usernameTextField.getText() + "'";
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(dbUrl, dbUsr, dbPass);
st = conn.createStatement();
rs = st.executeQuery(sql);
while(rs.next()){
String value = rs.getString("password");
text1 =value;
}
System.out.println(text1);
}catch(Exception e){
e.printStackTrace();
}finally{
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
when saving password you should save it encrypted and when you verify the password you should verify comparing the encrypted versions of the password as in.
String verifyLogin = " SELECT count(1) FROM user_account WHERE username = '" + usernameTextField.getText() + "' AND password =MD5('" + enterPasswordField.getText() +"')";
String insertFields3 = " UPDATE user_account SET password = MD5('" + enterPasswordField.getText() + "') WHERE username = '" + usernameTextField.getText() +"'";
I am trying to insert new data in a SQL database using a DAO. I have a boolean method for insert but there is a SQL error or database is missing. Database is not missing because I tested it and it displays everything from the table.
Here is the connection method
public Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
String dbURL = "jdbc:sqlite:studentdb.sqlite";
dbConnection = DriverManager.getConnection(dbURL);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
And the insert method
public boolean insertStu(Student stu) throws SQLException {
Connection dbConnection = null;
Statement statement = null;
ResultSet resultset = null;
boolean b = false;
try {
String query = "insert into studentdb (Name, Gender, DOB, Address, Postcode, StudentNumber, CourseTitle, StartDate, Bursary, Email) values (\""
+ stu.getName() + "\"," + "\"" + stu.getGender() + "\"," + "\"" + stu.getDob() + "\"," + "\""
+ stu.getAddress() + "\"," + "\"" + stu.getPostcode() + "\"," + "\"" + stu.getStudentNumber()
+ "\"," + "\"" + stu.getCourseTitle() + "\"," + "\"" + stu.getStartDate() + "\"," + "\""
+ stu.getBursary() + "\"," + "\"" + stu.getEmail() + "\")";
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
b = statement.execute(query);
} catch (SQLException s) {
throw new SQLException("Contact Not Added");
} finally {
if (dbConnection != null) {
dbConnection.close();
}
if (statement != null) {
statement.close();
}
if (resultset != null){
resultset.close();
}
}
return b;
}
I have tried the SQL query in different program where the connection method was Statement type and the insert method was still boolean but now the requirement is to use Connection class. Either way it should work but I don't understand way is not working. The Student object has get and set methods for its variables.
Any help would be much appreciated.
I have the following code running fine with one sql statement selectEmpShowDocs_SQL referring to schema1. In this scenario, I have hard coded the value of empID as 2 as shown in the sql below :
private String selectEmpShowDocs_SQL =
"SELECT " +
"emp_doc " +
"FROM " +
"schema1.emp_info " +
"WHERE " +
"doc_id = ? "+
"AND"+
"empID = 2";
Now, I have another sql statement which is retrieving the emp_id value and instead of hardcoding the value just like I did above for empID, I want to pass the value of emp_id obtained from the following sql statement to the above sql statement. This is the statement which is referring to schema2.
private String selectEmpIDSQL =
"SELECT " +
"emp_id " +
"FROM " +
"schema2.emp_id " +
"WHERE " +
"company_id = 435 "
I am wondering is it possible to connect with two different schemas with one prepared statement? Here someone mentioned that prepared statement is bound to a specific database and in that case if it's not possible, what would be the best approach for me?
Here is the full code that works fine for me using only the SQL query referring to schema1.
public List<EmployeeDocument> getEmployeeDocument(String docId, Integer employeeID) throws DaoException
{
StopWatch stopWatch = new StopWatch();
stopWatch.start();
DataSource ds = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<EmployeeDocument> empShowDocs = new ArrayList<EmployeeDocument>();
try {
ds = jdbcTemplate.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(selectEmpShowDocs_SQL);
logger.debug("sql query :" + selectEmpShowDocs_SQL);
System.out.println(selectEmpShowDocs_SQL);
pstmt.setString(1, docId);
logger.debug("sql parameters, docId:" + docId);
rs = pstmt.executeQuery();
while(rs.next()) {
EmployeeDocument empShowDocRecord = new EmployeeDocument();
empShowDocRecord.setEmp_Content(rs.getString("emp_doc")));
empShowDocs.add(empShowDocRecord);
}
} catch(Throwable th) {
throw new DaoException(th.getMessage(), th);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (pstmt != null) {
try {
pstmt.close();
} catch(SQLException sqe) {
sqe.printStackTrace();
}
pstmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
conn = null;
}
if (ds != null) {
ds = null;
}
}
return empShowDocs;
}
private String selectEmpShowDocs_SQL =
"SELECT " +
"emp_doc " +
"FROM " +
"schema1.emp_info " +
"WHERE " +
"doc_id = ? "+
"AND"+
"empID = 2";
private String selectEmpIDSQL =
"SELECT " +
"emp_id " +
"FROM " +
"schema2.emp_id " +
"WHERE " +
"company_id = 435 "
My method working only with StrictMode, when i delete StrictMode, my app after the run this method loading in the infinity... and never stop.
I don't know why, somebody can explain it ?
public void sending() {
Connection co = null;
Statement st = null;
try {
StrictMode.ThreadPolicy po = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(po);
Class.forName("com.mysql.jdbc.Driver");
co = DriverManager.getConnection(url2, user2, pass2);
st = co.createStatement();
Double bb = latitude;
Double bb1 = longitude;
String sql2 = "INSERT table (tab1, tab2) VALUES('" + bb + "', '" + bb1 + "')";
st.executeUpdate(sql2);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (st != null) {
co.close();
}
} catch (SQLException se) {
}
try {
if (co != null) {
co.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
}
Your have a problem in your Query it should be :
"INSERT Into table (tab1, tab2) VALUES('" + bb + "', '" + bb1 + "')"
and not :
"INSERT table (tab1, tab2) VALUES('" + bb + "', '" + bb1 + "')"
You missed Into in your query.
Note
You can get syntax error or Sql injection with your way i suggest to use PreparedStatement it's more secure and more helpful like this :
PreparedStatement preparedStatement =
connection.prepareStatement("INSERT into table (tab1, tab2) VALUES(?, ?)");
preparedStatement.setString(1, bb);
preparedStatement.setString(2, bb1);
I'm making some programme for checking approaches scales for different usernames. When I call function DodajObrisiPristupe(table, comboBox), it says database locked. I searched for solutions and all says that it's probably that I didn't close connection somewhere, but I can't find where. Can anyone please help me?
public void DodajObrisiPristupe(JTable tabela, JComboBox<String> korisnickoime)
{
DefaultTableModel model = (DefaultTableModel)tabela.getModel();
for (int i = 0; i < model.getRowCount(); i++)
{
String serijskibroj = model.getValueAt(i, 2).toString();
boolean pristup = (Boolean)model.getValueAt(i, 4);
if(ProveriDaLiPostojiPristup(serijskibroj, korisnickoime.getSelectedItem().toString()) == true)
{
if(pristup == false)
ObrisiPristup(serijskibroj, korisnickoime.getSelectedItem().toString());
}
else
{
if(pristup == true)
DodajPristup(serijskibroj, korisnickoime.getSelectedItem().toString());
}
}
}
public boolean ProveriDaLiPostojiPristup(String serijskibroj, String korisnickoime)
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:" + naziv + ".db");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM PRISTUPI;");
while(rs.next())
{
if(Decrypt(rs.getString("korisnickoime")).equals(korisnickoime) && Decrypt(rs.getString("vage")).equals(serijskibroj))
return true;
}
rs.close();
stmt.close();
c.close();
}
catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
return false;
}
public void DodajPristup(String serijskibroj, String korisnickoime)
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:" + naziv + ".db");
stmt = c.createStatement();
String sql = "INSERT INTO PRISTUPI (KORISNICKOIME,VAGE) " +
"VALUES ('" + Encrypt(korisnickoime) + "', '" + Encrypt(serijskibroj) + "');";
stmt.executeUpdate(sql);
stmt.close();
c.close();
}
catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
}
public void ObrisiPristup(String serijskibroj, String korisnickoime)
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:" + naziv + ".db");
stmt = c.createStatement();
String sql = "DELETE from PRISTUPI where KORISNICKOIME = '" + Encrypt(korisnickoime) + "' AND VAGE = '" + Encrypt(serijskibroj) + "';";
stmt.executeUpdate(sql);
stmt.close();
c.close();
}
catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
}
You are not closing your connection in ProveriDaLiPostojiPristup(String, String).
You should always wrap your connections in try-with-resources or try-finaly, so they are always closed.
c = DriverManager.getConnection("jdbc:sqlite:" + naziv + ".db");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM PRISTUPI;");
while(rs.next())
{
if(Decrypt(rs.getString("korisnickoime")).equals(korisnickoime) &&
Decrypt(rs.getString("vage")).equals(serijskibroj))
return true;
}
rs.close();
stmt.close();
c.close();
What happens, is that your method returns true, but because the execution is stopped there, it won't execute the lines below it. This can be countered if you wrap the statements in a try with resources block:
try(c = DriverManager.getConnection("jdbc:sqlite:" + naziv + ".db")){
try(stmt = c.createStatement()){
try(ResultSet rs = stmt.executeQuery("SELECT * FROM PRISTUPI;")){
while(rs.next())
{
if(Decrypt(rs.getString("korisnickoime")).equals(korisnickoime) && Decrypt(rs.getString("vage")).equals(serijskibroj))
return true;
}
}
}
}