Creating SQLite database in intellij - java

I have to create a SQLite database that I will ultimately have to insert lines of data from a parsed .csv file. The issue that I'm having is creating the SQLite database in the intellij idea. Using the code below I continue to get the "No suitable driver" error. I believe that I've added the classpath correctly by using Project Structure-> Modules-> Add then selecting my downloaded SQLite .jar file, which in this case is sqlite-jdbc-3.30.1 (1).jar
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
public class mint {
public static void createNewDatabase(String fileName) {
String url = "C:\\SQLite\\sqlite-jdbc-3.30.1 (1).jar" + fileName;
try {
Connection conn = DriverManager.getConnection(url);
if (conn != null) {
DatabaseMetaData meta = conn.getMetaData();
System.out.println("The driver name is " + meta.getDriverName());
System.out.println("A new database has been created.");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
System.out.println("An error occurred while connecting MySQL database");
}
}
public static void main(String[] args) {
createNewDatabase("input-filename.db");
}
}
Screenshot of output

You need to read this tutorial - URL should be like this
String url = "jdbc:sqlite:C:/sqlite/" + fileName;

Related

format for Using Sqlite Database (from Java Package) to the Java Code inside `driverManager` to make connection

I have inserted my SQLite.db file inside of package named newpackage
Location of database file I inserted here isCollegeProject\src\operalogsapp\newpackage\SQLite.db
Now I want to get this database, so I want the correct format for inserting it to driver manager.
public class databaseConnection {
public static Connection con;
public static Connection getDBConnection(String username, String password, Integer portNumber, String serviceName){
try {
//Register the JDBC driver
System.out.println("before className");
Class.forName("org.sqlite.JDBC");
System.out.println(con==null);
System.out.println("Registered to the JDBC driver");
//Open the connection
if("V50700_HOTEL".equals(username) && "V50700_HOTEL".equals(password) && portNumber==1501 && "operal".equals(serviceName)){
con=DriverManager.getConnection("jdbc:sqlite:C:\\Users\\absasahu\\Documents\\db\\SQLite.db");
//inside the getConnection (above line) I want to get correct location of database to enter.
System.out.println("DriverManager connected to db");
}
} catch (ClassNotFoundException | SQLException ex) {
System.out.println("Exception : "+ex);
//Logger.getLogger(dbCoonectionCode.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("DFHUDSBFSDF");
return con;
}
Any help will be appreciated.
"jdbc:sqlite:sqlite_database_file_path", in your case from your code:
"jdbc:sqlite:C:/Users/absasahu/Documents/db/SQLite.db"
Regarding your question using a relative path:
"jdbc:sqlite:SQLite.db"
See also the answers at Set path to a jdbc SQLite database, where it will be located
A complete example with class file and driver in the same directory (unfortunately on a unix machine):
// mkdir collegeproject
// cd collegeproject
// curl -LJO https://github.com/xerial/sqlite-jdbc/releases/download/3.36.0.3/sqlite-jdbc-3.36.0.3.jar
// javac SqliteTest.java
// java -classpath ".;sqlite-jdbc-3.36.0.3.jar" SqliteTest # in Windows
// java -classpath ".:sqlite-jdbc-3.36.0.3.jar" SqliteTest # in Unix
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqliteTest {
public static void main(String[] args)
{
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:sqltest.db");) {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate("drop table if exists book");
statement.executeUpdate("create table book (id integer, title string)");
statement.executeUpdate("insert into book values(1, 'SQLite with JDBC for Beginners')");
try (ResultSet rs = statement.executeQuery("select * from book")) {
while (rs.next()) {
System.out.println("id = " + rs.getInt("id"));
System.out.println("title = " + rs.getString("title"));
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
}
$ javac SqliteTest.java
$ java -classpath ".:sqlite-jdbc-3.36.0.3.jar" SqliteTest
id = 1
title = SQLite with JDBC for Beginners
$

Connect Oracle Java stored procedure to Snowflake

I was trying to have snowflake db connection using oracle Java stored procedure. But it's giving me error
ORA-29532: Java call terminated by uncaught Java exception: java.sql.SQLException: No suitable driver found
I have already downloaded snowflake-jdbc-3.6.19-javadoc.jar from related source.
Below is sample code of java class which will be called from oracle java procedure.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class SnowflakeDriverExample
{
public static void testdata() throws Exception
// public static void main(String[] args) throws Exception
{
// get connection
System.out.println("Create JDBC connection");
Connection connection = getConnection();
System.out.println("Done creating JDBC connectionn");
// create statement
System.out.println("Create JDBC statement");
Statement statement = connection.createStatement();
System.out.println("Done creating JDBC statementn");
// query the data
System.out.println("Query demo");
ResultSet resultSet = statement.executeQuery("SELECT DATA_ID FROM TEMP_TABLE");
System.out.println("Metadata:");
System.out.println("================================");
// fetch metadata
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
System.out.println("Number of columns=" +
resultSetMetaData.getColumnCount());
statement.close();
}
private static Connection getConnection()
throws SQLException
{
try
{
Class.forName("net.snowflake.client.jdbc.SnowflakeDriver");
}
catch (ClassNotFoundException ex)
{
System.err.println("Driver not found");
}
// Class.forName("net.snowflake.client.jdbc.SnowflakeDriver");
// build connection properties
Properties properties = new Properties();
properties.put("user", "XXX"); // replace "" with your username
properties.put("password", "XXXX"); // replace "" with your password
properties.put("account", "XXXX"); // replace "" with your account name
properties.put("db", "db1"); // replace "" with target database name
properties.put("schema", "MYSCHEMA"); // replace "" with target schema name
//properties.put("tracing", "on");
// create a new connection
String connectStr = null;//System.getenv("SF_JDBC_CONNECT_STRING");
// use the default connection string if it is not set in environment
if(connectStr == null)
{
connectStr = "jdbc:snowflake:XXXX"; // replace accountName with your account name
}
return DriverManager.getConnection(connectStr, properties);
}
}
How to import/integrate this driver for java stored procedure?

Table not found error in eclipse IDE, what to do?

I recently started working on JDBC and I got an Error as Table not found
Table TRIAL not found; SQL statement:
insert into trial values(1,'hello') [42102-73]
Here is my code, also I have already created a table in h2 DB
package trial1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Customer {
public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:h2:~/test","Aziz", "password");
Statement st = conn.createStatement();
String str = "insert into trial values(1,'hello')";
st.execute(str);
System.out.println("Succes");
}
catch(Exception e) {
e.printStackTrace();
}
}
}

Java - DriverManager.getConnection Access

i have the following code to test a link to a access database on a new server, everything works with the existing server and i am able to access the folder. !if.exists returns true and i can open the data base using Runtime.getRuntime().exec("run......... + f); so i know it can see the database. im unable to get a reason for the fail but its 100% failing at Connection conn = de.....
can anyone help me.
running gives following output - Java result: -1073741811
package testing;
import connections.LocalProperties;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewClass {
public static void main(String[] args) {
try {
File f = new File("\\\\***\\***\\****\\***.accdb");
if (!f.exists()) {
System.out.println("file does not exist" + f.getAbsolutePath());
return;
} else {
System.out.println("file does exist" + f.getAbsolutePath());
}
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + f.getAbsolutePath();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String m_URLString = url;
String m_UserName = System.getProperty("user.name");
String m_Password = "*******";
Connection conn = DriverManager.getConnection(m_URLString, m_UserName, m_Password);
conn.close();
} catch (SQLException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
When running i get the following popups:
Java.exe
If you were in the middle of something, the information might be lost, for more information click here
Error signature
App name:java.exe appver 7.0.30.5 modname:msvcr80.dll
I think you are missing this line-
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

JDBC connectivity with open office database

I am using openoffice database for my project....Please help me know how to connect to open office database using JDBC.
Below code is for JAVA. Transform to JSP accordingly.
import java.text.ParseException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main
{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws ParseException
{
try
{
String db_file_name_prefix = "c:\\mydbdir\\mydb";
Connection con = null;
// Load the HSQL Database Engine JDBC driver
// hsqldb.jar should be in the class path or made part of the current jar
Class.forName("org.hsqldb.jdbcDriver");
// connect to the database. This will load the db files and start the
// database if it is not alread running.
// db_file_name_prefix is used to open or create files that hold the state
// of the db.
// It can contain directory names relative to the
// current working directory
con = DriverManager.getConnection("jdbc:hsqldb:file:" + db_file_name_prefix, // filenames
"sa", // username
""); // password
Statement statement = con.createStatement();
//look at " for table name
ResultSet rs = statement.executeQuery("SELECT * FROM \"User\"");
//print the result set
while (rs.next())
{
System.out.print("ID: " + rs.getString("ID"));
System.out.print(" first name: " + rs.getString("firstname"));
System.out.println(" last name: " + rs.getString("lastname"));
}
statement.close();
con.close();
} catch (SQLException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
} catch (ClassNotFoundException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Never tried it but seems like OpenOffice uses HSQLDB database underneath in file mode. Looks like you can connect to this HSQLDB database directly: Java: Creating a JDBC Connection to OpenOffice.Org Databases.
See also:
How to connect to a "normal" (not embedded) HSQL database?

Categories