database file is locked" when chrome browser is running - java

My goal is to get chrome history, this works fine. But my problem is getting "The database file is locked" only when chrome browser is running.
How can I fix this problem?
Can I stop database chrome browser?
this my code:
public class GetChromeHistory
{
public static void main (String[] args)
{
Connection connection= null;
ResultSet resultSet = null;
Statement statement = null;
try
{
// We think, but are not sure, that the line below registers the sqlite drive with JDBC.
Class.forName("org.sqlite.JDBC");
connection = DriverManager
.getConnection("jdbc:sqlite:db.db");
statement = connection.createStatement();
//problem occurs on line below, database file is locked
resultSet = statement
.executeQuery("SELECT * FROM urls where visit_count > 0");
while(resultSet.next())
{
//eventually save into a set or list
System.out.println ("URL [" + resultSet.getString("url") + "]" +
", visit count [" + resultSet.getString("visit_count") + "]");
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
resultSet.close();
statement.close();
connection.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}

Related

How do i verify whether my code has access to table

I am learning Java getting trouble in JDBC connection.
Following is my code:
public class DemoPro {
public void test() {
Connection con;
Statement stmt;
ResultSet rs;
System.out.println("Looking for connection");
try{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String dburl="jdbc:ucanaccess://E://WEB Project//SCMPayBoard//Database/SCMEmpPayment.accdb";
con=DriverManager.getConnection(dburl,"","");
System.out.println("Connection successfully");
stmt=con.createStatement();
String verify = "Select * from TestTable";
stmt.executeQuery(verify);
rs = stmt.getResultSet();
System.out.println("Executing Query");
while(rs.next())
{
System.out.println("Result/n/n/n");
System.out.println(rs.getString(2) + " : " + rs.getString(3));
}
System.out.println("Closing Connection");
con.close();
}catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(DemoPro.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
DemoPro dp=new DemoPro();
dp.test();
}
}
Output :
Looking for connection
Connection successfully
Executing Query
Closing Connection
BUILD SUCCESSFUL (total time: 1 second)
All sysout is executing but Table data is not fetched
How do i know Table is getting access or not
What should i do getting no result as expected

Bulk Deletes Very Slow on SQLite using JDBC

I have a program that trims items from a SQLite database based on a timestamp field. It seems when I run it on a large existing database that it takes quite a very long time and hogs up the resources on my already very low end embedded machine.
Can anyone suggest any ideas on how to improve my code to get it to run better/faster?
Call from main program:
query = SQLiteInterface.getInstance().delete(entry, "SampleInfo_source_timestamp < '" + timestamp + "'");
dbCall(query);
SQLiteInterface delete method:
/**
* This creates a SQLite formatted 'delete' statement that allows for where clauses
*
* #param table - The table that the items are being selected from
* #param filters - The list of where clauses
* #return - A SQLite formatted delete query
*/
public String delete(String table, String filters)
{
if (filters == null)
{
return "delete from " + table;
} else
{
return "delete from " + table + " where " + filters;
}
}
Code that actually sends the DB Command using JDBC
/**
*
*
* #param query - A SQLite formatted DB query
*/
public void dbCall(String query)
{
// Good practice to create a new statement and result set instead of reusing
Statement stmt = null;
Connection conn = null;
ResultSet rs = null;
try
{
// Fetch the query and the request out of the QueryRequest object
conn = cpds.getConnection();
conn.setAutoCommit(false);
// Make sure the query request isn't empty, if it is, there is no point in sending it to the DB
if (!query.isEmpty())
{
// Initialize the new statement
stmt = conn.createStatement();
stmt.executeUpdate(query);
}
conn.commit();
}
catch (SQLException e)
{
if (e.getMessage().contains("no such column"))
{
// This table is not one that needs to be cleaned up.
}
else
{
errorLog.error("", e);
// Table busy, try again.
dbCall(query);
}
}
catch (Exception e2)
{
errorLog.error("", e2);
}
finally
{
if (rs != null)
{
try
{
rs.close();
}
catch (SQLException e)
{
errorLog.error("Failed to close JDBC result set.");
}
}
if (stmt != null)
{
try
{
stmt.close();
}
catch (SQLException e)
{
errorLog.error("Failed to close JDBC statement.");
}
}
if (conn != null)
{
try
{
conn.close();
}
catch (SQLException e)
{
errorLog.error("Failed to close JDBC connection.");
}
}
}

SQLite Java JDBC Insert

Following is my Java code. In linux, it is working fine but in Windows I'm unable to insert data into the database on local disk. In NetBeans get it all right but .jar file not. JDBC driver see be good.
Connecting to database:
public static Connection connectToDb() {
try {
Connection connection = null;
DriverManager.registerDriver(new org.sqlite.JDBC());
//LINUX PATH
if (OSDetector.isLinux()) {
connection = DriverManager.getConnection("jdbc:sqlite:/home/" + userNameLinux + "/PDFMalwareDataAnalyser/DatabaseSQLite/database.db", NAME, PASSWORD);
//WINDOWS PATH
} else {
connection = DriverManager.getConnection("jdbc:sqlite:C:\\PDFMalwareDataAnalyser\\DatabaseSQLite\\database.db", NAME, PASSWORD);
}
connection.setAutoCommit(true);
if (connection != null) {
System.out.println("Otvorená.");
}
return connection;
} catch (SQLException e) {
System.err.println(e.getClass().getName() + e.getMessage());
// System.exit(0);
}
return null;
}
Insertion:
public void insertDataToDatabase(int idReport) throws SQLException {
connection = new SQLiteJDBC().connectToDb();
PreparedStatement insertCommunication = connection.prepareStatement("insert into table_communication values(?,?);");
insertCommunication.setString(2, communicationsFinal.toString());
try {
insertCommunication.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
insertCommunication.close();
connection.close();
System.out.println("1. --- Insert do tabuľky TABLE_COMMUNICATION OK ---");
}
Try this:
connection = DriverManager.getConnection("jdbc:sqlite:C:/PDFMalwareDataAnalyser/DatabaseSQLite/database.db")

Trying to connect to a database in Eclipse ee

I have been trying this for a few hours now but with no success. I downloaded the JDBC driver and it shows that it is one of my referenced libraries under my Package Explorer in Eclipse but every time I try to run my code I get errors. My database is fine as I can change it and view it from the MySQL Command Line Client.
I actually followed a guides directions on how to do it, only replacing the information from their database to information about mine.
import java.sql.*;
public class FirstExample {
//JDBC Driver Name and Database URL
final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final static String DB_URL = "jdbc:mysql://localhost/test_database";
//Database Credentials
static final String USER = "user_one";
static final String PASS = "User_one_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//Register JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
//Open a Connection
System.out.println("Connecting to the Database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//Execute a Query
System.out.println("Creating Statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM user";
ResultSet rs = stmt.executeQuery(sql);
//Extract Data from Result Set
while (rs.next()) {
//Retrieve by Column Name
int id = rs.getInt("id");
String first = rs.getString("name");
//Display Values
System.out.print("ID: " + id);
System.out.println("Name: " + first);
}
//Clean Up Environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
//Handle Errors For JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle Errors for Class.forName
e.printStackTrace();
} finally {
//Finally Block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
//Nothing We Can Do
}
try {
if (conn != null)
conn.close();
} catch (Exception se) {
se.printStackTrace();
}//End Finally Try
}//End Try
System.out.println("Goodbye!");
}//End Main
}//End First Example
Here is the error I get http://pastebin.com/hLSxV3aq

java.sql.SQLException: Invalid handle

I'm trying to teach myself how to connect to a msaccess database in java.
I have set up a class to access the database as follows
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public abstract class AccessDBConnect2 {
public static Connection connect(){
String fileName = "C:/Users/Bridget/Documents/EmployeeSys.accdb";
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+fileName;
con = DriverManager.getConnection(url,"","");
} catch (Exception e) {
// Handle exceptions ...
System.out.println(e.toString());
System.out.println("A problem accessing the database");
e.printStackTrace();
} finally {
try { if(con!=null) {con.close();} } catch (Exception e) {}
}
return con;
}
public static void closeConnection(Connection conn){
try{
conn.close();
}catch (Exception e){
}
}
Then I have my code which is just trying to select everything from the table.
I have created the table in msAccess and the code seems to get through the connect method in the above code without any problems, indicating it is finding the database and accessing it somewhat. The problem happens when I call the prepareStatement using the connection, i.e. code line:
stm = conn.prepareStatement(sql);
The full code is:
import java.sql.*;
public class Program2{
public static void main(String[] args) {
try{
// Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
// Establishing db connection
Connection conn = AccessDBConnect.connect();
// Displaying all records from employee file
System.out.println("Display records of all employees");
display(conn);
// Closing the connection
AccessDBConnect.closeConnection(conn);
}catch (Exception e){
System.out.println("Error");
}
}
// Display details of all employees
public static void display(Connection conn){
PreparedStatement stm = null;
// SQL statement
String sql = "SELECT * FROM Employee";
ResultSet rs;
try {
stm = conn.prepareStatement(sql); // Prepare the SQL statement
rs = stm.executeQuery(); // Execture the SQL statement
// Navigate through the ResultSet and print
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
String address = rs.getString("address");
System.out.println("ID: \t \t" + id);
System.out.println("Name: \t \t" + name);
System.out.println("Gender: \t" + gender);
System.out.println("Address: \t" + address);
System.out.println(" ");
}
// Closing the resultSet
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void test(){
int a = "hello";
}
}
You are receiving the error because when you try to call .prepareStatement the connection is closed. Your AccessDBConnect2 class contains a finally block that closes the connection before it returns. Fix that class so it leaves the connection open.
By the way, the JDBC-ODBC Bridge has been removed from Java 8 and is effectively obsolete. You might be interested in this alternative:
Manipulating an Access database from Java without ODBC
I've removed the obviously incorrect answer :) another possibility:
I would think the issue is in your connection to the database, try changing 'C:/Users/Bridget/Documents/EmployeeSys.accdb' to 'C:\\Users\Bridget\Documents\EmployeeSys.accdb'

Categories