How to read an sqlite database file in Java? (Package) - java

Okay i know i have to use the JDBC etc, but im not sure how to implement the jar into my code, i have a basic code to open the file etc, but how can i actually incorporate the sqlite jar alongside my java class file to be run anywhere?
So for example i have a folder with:
Test.class
new.db
sqlite.jar
In Test.class i have the basic connection and imports:
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:new.db");
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT empname FROM employee");
while (resultSet.next()) {
System.out.println("EMPLOYEE NAME:"
+ resultSet.getString("empname"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
So how can i have this simple little script portable?
Thanks

Add the sqlite.jar to you classpath:
java -cp .;./sqlite.jar Anima
This should work. If not - please show your error message.
Edit
tested and verified. Create/Have a folder with the following content:
./project
Anima.class
sqlite.jar
then cd to folder project and do a
java -cp .;./sqlite.jar Anima
It works as expected on my machine.

Related

How to set class path and connect to DB2 using java

I don't know how to set the classpath in a java project.
This is the code that I run:
try { Class.forName("com.ibm.db2.jdbc.app.DB2Driver");
} catch (ClassNotFoundException e) {
System.out.println("Please include Classpath Where your DB2 Driver is located");
e.printStackTrace();
return;
} System.out.println("DB2 driver is loaded successfully");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset=null;
boolean found=false;
try {
conn = DriverManager.getConnection("jdbc:db2:DB2PDBA","USERID","PASSWORD");
if (conn != null)
{
System.out.println("DB2 Database Connected");
}
else
{
System.out.println("Db2 connection Failed ");
}
and my Error is:
java.lang.ClassNotFoundException: com.ibm.db2.jdbc.app.DB2Driver
When we say put something within classpath, it means:
you should put the related jar files that your app needs to run
the entire application somewhere in your project.
Please follow the link below to create a DB2 application -> IBM Example about DB2
The only thing you need to do is to:
Add this into your project
change the credentials and db information
add the db2 jdbc jar file to your project

IntelliJ extract data from sqlite database file?

I just started with sqlite and I stuck with a strange (maybe just for me) phenomenon. When I connect the testDB.db file in java, and make one or some query, the data and the table itself is disappearing. The consol said that SQL error or missing database, and when I check the database file in cmd, the situation is really that; there is no data in the file. Could anybody help me out with this basic problem? (I suppose that this is just because of the lack of my knowledge in this topic, but I'm open to new information)
public class jdbcTest{
public static void main(String[] strg) {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Username\\Documents\\sqlite\\testDB");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30);
//statement.executeUpdate("drop table if exists person");
ResultSet rs = statement.executeQuery("select * from company");
while (rs.next()){
System.out.print("id = "+rs.getInt("id")+" ");
System.out.println("name = "+rs.getString("name"));
}
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
finally {
try {
if (connection!=null){
connection.close();
}
}
catch (SQLException e){
System.err.println(e);
}
}
}
}
When opening a nonexistent database file, SQLite will happily create a new, empty one.
The file name you're giving to getConnection does not actually point to the database you saved.

MySQL access from Hadoop MapReduce

I want to access MySQL database within my MapReduce program. I have a DBConnection class and I getConnection within the mapper class.The db.properties file is in place and with correct path mentioned in the DBConnection class.
Everytime I run the hadoop jar command I get error java.io.FileNotFoundException: db.properties (No such file or directory).
How can I resolve this?
Establishing DB connection in mapper:
Connection con = DBConnection.getConnection();
PreparedStatement pst = null;
String selectRows = "Select count(*) from sample";
Thanks
Try with this:
Prior Java 1.7:
InputStream input = YourClassName.class.getResourceAsStream("/db.properties");
try {
prop.load(input);
} catch (IOException ex) {
}finally{
input.close();
}
Java 1.7 and ahead:
try (InputStream input = YourClassName.class.getResourceAsStream("/db.properties")) {
prop.load(input);
} catch (IOException ex) {
}

What is causing the "near ".": syntax error" in my SQLite query?

I am trying to output my table as a .csv file. I am using the sqlite-jdbc java library to execute my query. Here are the statements:
.mode csv
.output test.csv
select * from geninfo;
.output stdout
and this is my java code:
try {
try {
// create a database connection
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException ex) {
Logger.getLogger(SQLite.class.getName()).log(Level.SEVERE, null, ex);
}
connection = DriverManager.getConnection("jdbc:sqlite:702Data.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("create table if not exists geninfo (id TEXT, DeviceID TEXT)");
statement.executeUpdate(".mode csv");
statement.executeUpdate(".output test.csv");
statement.executeUpdate("select * from geninfo;");
statement.executeUpdate(".output stdout");
ResultSet rs = statement.executeQuery("select * from geninfo");
while (rs.next()) {
// read the result set
System.out.println("DeviceID = " + rs.getString("DeviceID"));
System.out.println("id = " + rs.getInt("id"));
}
} catch (SQLException e) {
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
// connection close failed.
System.err.println(e);
}
}
}
I have tried adding parenthesis around the period and also removing the period and both cause the same syntax error.
Those commands are SQLite console commands, not pure SQL. JDBC can only handle SQL.
If you want to do this from java, try executing the shell command to open the console using ProcessBuilder and feed it the commands via its InputStream.
However, if calling from java is not necessary, you may be better served writing a shell script of some sort and using that directly, or calling the script from java.
If all you are using SQLite for is to parse the CSV file, consider not using SQLite at all and instead load the data directly from the file into your code using one of the several open source CSV parsing libraries out there. This approach will be order of magnitude faster and simpler.

Class.forName(JDBC_DRIVER); Only working in 1 of my 2 programs when the code is the same. Why?

I have 1 basic program and 1 app, My basic program with this works ( DB_URL, USER, PASS, JDBC_DRIVER all correct and functional) and I am able to get information from my MySQL DB. The code consist of this:
try {
// STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
// STEP 3: Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT distinct tags FROM items";
ResultSet rs = stmt.executeQuery(sql);
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
String itemRoles = rs.getString("tags");
//Add it to the ArrayList.
itemRolesList.add(itemRoles);
// Display values
System.out.print("TAGS: " + itemRoles + "\n");
}
// STEP 6: 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 (SQLException se) {
se.printStackTrace();
}// end finally try
}// end try
But when I try to apply this same code to my app (inside a Fragment in my OnCreateView()) I get this:
"java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"
and it is at this line of code:
Class.forName(JDBC_DRIVER);
I added the "mysql-connector-java-5.1.23-bin.jar" and it is in my Reference Library in both my program and app. Does anyone know why inside my app it gives me this error?
Make sure that you have driver jar in your classpath.
Please verify that you have jar file inside lib folder is not the empty jar file.sometime during wrong confuguration it shows a empty jar file.
please go to project properties-->buildpath-->libraries
Check out the jar file you have added is not blank.

Categories

Resources