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.
Related
I'm developing a desktop app to organize different events, thus creating a DB for each event. So far, I've managed to create a DB with whatever name the user wants, using a simple GUI.
However, I can't create tables nor columns for said database, even though it's exactly the same syntax I use in SQL Server Manager.
My code so far:
public static void creDB(String db_name, String table_name){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(connectionUrl);
String SQL = "CREATE DATABASE " + db_name;
stmt = conn.createStatement();
int result = stmt.executeUpdate(SQL);
String SQL3 = "USE " + db_name;
boolean ree = stmt.execute(SQL3);
String SQL4 = "GO";
boolean rr = stmt.execute(SQL4);
if (result == 0){
System.out.println("Se insertó :D!");
String SQL2 = "CREATE TABLE Pepe(Name_emp INT NOT NULL PRIMARY KEY)";
int res = stmt.executeUpdate(SQL2);
if (res == 0)
System.out.println("GRACIAS DIOS");
}else
System.out.println("Raios shico");
}catch (Exception e) {e.printStackTrace();}
finally {
if (rs != null) try {rs.close();} catch (Exception e) {e.printStackTrace();}
if (stmt != null) try {stmt.close();} catch (Exception e) {e.printStackTrace();}
if (conn != null) try {conn.close();} catch (Exception e) {e.printStackTrace();}
}
}
The error I get is when I try to actually use the DB, using the use [DB name] go; I tried already using that same syntax in one single SQL statement, however it didn't work, so I tried doing it separately and got this error:
com.microsoft.sqlserver.jdbc.SQLServerException: Could not find stored procedure 'GO'.
I know the code above looks like a mess, and it is, but it's just for testing purposes since I'm new to doing DB-related projects with Java; I mixed-matched some of the concepts of this site, which were successful up until the creation of the tables.
I know there's a better way of managing several databases, but as I said, I'm just starting so any advice would be greatly appreciated.
You should not use statements like USE <dbname> when using JDBC, it may lead to unexpected behavior because parts of the driver may still use metadata for the original connected database. You should either use setCatalog on the current connection to switch databases or create an entirely new connection to the new database.
In short, after creating the database, you should use:
conn.setCatalog(db_name);
That's it.
Also, go is not part of the SQL Server syntax, it is only used by tools like the Management Studio, see What is the use of GO in SQL Server Management Studio & Transact SQL? The equivalent in JDBC is to simply execute the statement.
I am trying to create a new database file named test in the folder D:\sqlite, using JDBC, as follows:
import java.sql.*;
public class Class1 {
private static void createNewDataBase(){
String url = "jdbc:sqlite:D:sqlite/";
Connection conn = null;
Statement statement = null;
try{
conn = DriverManager.getConnection(url);
System.out.println("Connection Established");
statement = conn.createStatement();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
try {
statement.execute("CREATE DATABASE test");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally{
try{
if(statement != null)
statement.close();
}catch(SQLException e){
System.out.println(e.getMessage());
}
try{
if(conn != null)
conn.close();
}catch(SQLException e){
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args){
createNewDataBase();
}
}
When I run the project, I get the following output:
Connection Established
[SQLITE_ERROR] SQL error or missing database (near "DATABASE": syntax error)
Process finished with exit code 0
It says the syntax is wrong but I can't find the error. I've looked for answers for similar questions, but none solved my problem. Can anyone tell me what's the problem? Thanks in advance!
As already stated by #Andreas, there is no CREATE DATABASE SQL statement for SQLite. To create a new SQLite database you need to merely make a connection to one and it is automatically created (you do however need to ensure that the D:/sqlite/ path already exists within the local file system).
The following code should create an empty (no tables) SQLite Database named MyNewDatabase.sqlite within the folder sqlite located in the root of drive D of your local file system:
String dbPath = "D:/sqlite/MyNewDatabase.sqlite";
Connection conn = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + dbPath;);
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
catch (SQLException ex) {
ex.printStackTrace();
}
finally {
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) { e.printStackTrace(); }
}
Now you need to create one or more Tables for your new database to make it useful. SQLite does accept the CREATE TABLE SQL statement and you could do this through the same connection if desired.
The database exists, it has been connected i.e the database is the connection, which is basically the file. Hence there is no SQL for CREATE DATABASE.
Inside the database you would typically create tables (and perhaps other components).
e.g. CREATE TABLE mytable (mycolumn TEXT, myothercolumn INTEGER) which would create a table named mytable with 2 columns mycolumn and myothercolumn (the former being defined with a column type of TEXT, the latter with a column type of INTEGER).
As such, if you were to change :-
statement.execute("CREATE DATABASE test");
to :-
statement.execute("CREATE TABLE mytable (mycolumn TEXT, myothercolumn INTEGER)");
Note you'd only want to do this once, otherwise it would fail as the table already exists, so you could use CREATE TABLE IF NOT EXISTS mytable (mycolumn TEXT, myothercolumn INTEGER), of cousre it depends upon your requirements.
You may find that it will work. Obviously you will need to do other things such as add some data as the table will be empty.
Perhaps then try
statement.execute("INSERT INTO mytable VALUES('fred',100)");
Every time this is run a new ROW will be added to the table name mytable.
Here is the code
import java.sql.*;
public class Insertdb {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con= DriverManager.getConnection("jdbc:odbc:Dsn1");
PreparedStatement ps= con.prepareStatement("insert into Table1 values (?,?,?)");
ps.setInt(1,1);
ps.setString(2,"Sachin");
ps.setInt(3,25000);
int i=ps.executeUpdate();
if(i>0)
{
System.out.println(i +"records inserted");
}
}
catch(Exception e)
{
System.out.println(e);
}
// TODO code application logic here
}
}
The data base used is MS Access 2013.
The output of the above code on the console is: 1 records inserted
But when i open the database the record is not inserted. Is there any thing wrong in the code? If not what could be going wrong?
also add at the end.
finally{
con.commit();
ps.close();
con.close();
}
Any Transaction from program to database must be committed to get reflected in JAVA.
Try doing con.commit();
Try to use finally in your code if you are connecting with database or perform file operations.Because whatever happened on try block the finally block always executed.so you can use finally block for closing the database connection and close the file and commit or rollback the database records.
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.
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.