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);
Related
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.
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 a problem with line pstmt.setLong(1, id);. I get an error that the value is not set for the parameter number 1. If I use the String SQL without the question mark, it works. Also, when I use ARM the PreparedStatement and ResultSet are not automatically closed so I have to close them, and finally doesn't seem to work either
#Override
public Company getCompany(long id) {
Connection con = ConnectionPool.getInstance().getConnection();
String sql = "SELECT * FROM Company WHERE ID=?";
//String sql = "SELECT * FROM Company WHERE ID=" + id;
Company company = new Company();
try (
PreparedStatement pstmt = con.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();)
{
pstmt.setLong(1, id);
if (rs.next()) {
company.setId(rs.getLong(1));
company.setCompName(rs.getString(2));
company.setPassword(rs.getString(3));
company.setEmail(rs.getString(4));
} else {
System.out.println("Company with ID: " + id + " could not be found\n");
}
pstmt.close();
rs.close();
} catch (SQLException e) {
CouponSystemException ex = new CouponSystemException("Company with ID: " + id + " could not be retrieved\n", e);
System.out.println(ex.getMessage());
System.out.println(e);
}
ConnectionPool.getInstance().returnConnection(con);
return company;
}
Set the parameter before executing the query.
Also, You don't need to close Statement and result sets defined in try-with-resource statements as they'll be closed automatically when you leave the try scope.
try(PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setLong(1, id);
try(ResultSet rs = pstmt.executeQuery()) {
// do stuff
}
}
You need to set the PreparedStatement's parameters before executing it. Also note that this you're using the try-with-resource syntax you shouldn't close the resources yourself:
try (PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setLong(1, id);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
company.setId(rs.getLong(1));
company.setCompName(rs.getString(2));
company.setPassword(rs.getString(3));
company.setEmail(rs.getString(4));
} else {
System.out.println("Company with ID: " + id + " could not be found\n");
}
}
} catch (SQLException e) {
CouponSystemException ex = new CouponSystemException("Company with ID: " + id + " could not be retrieved\n", e);
System.out.println(ex.getMessage());
System.out.println(e);
}
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 "
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;
}
}
}
}