package com.example.financecontrol;
import java.sql.*;
public class DBController {
public static Connection Connector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:FinanceControl.sqlite");
return conn;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
}
Is there a way to initialise database with some data if it does not exist. The problem is that I want to add some tables and configs while launching the application for the first time?
What I needed is "CREATE TABLE IF NOT EXISTS" statement. It worked properly!
Related
I have requirement where I need to read data from multiple rdbms tables which are present different databases. I have a regular connection class which returns a connection from its getConnection() method as below.
public class DbManager {
private static Connection connection;
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
if(connection == null) {
connection = DriverManager.getConnection("jdbc:mysql://localhost:portnumber", "username", "password");
return connection;
} else {
return connection;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
private DbManager() {
}
}
But this works only for one database. I have multiple databases in MySql, Oracle, Postgres and I have to read all the tables in all of those databases.
Is there a way to create connections for multiple databases using the same class or is there a different way to implement that ?
Hello guys so I have this simple java to do and I am trying to connect to an sqlite database from eclipse but it doesn't work at all.
Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseConnection {
private String pathDB="C:\\sqlite\\test.db";
private Connection connection=null;
private Statement statement=null;
public DatabaseConnection(String path){
pathDB= path;
}
public void connect () {
try {
Class.forName("org.sqlite.JDBC");
connection= DriverManager.getConnection("jdbc:sqlite:" + pathDB);
statement= connection.createStatement();
System.out.println("Connection to " + pathDB + " "+ "successful");
} catch (ClassNotFoundException notFoundException) {
notFoundException.printStackTrace();
System.out.println("Connection Error!");
} catch (SQLException sqlException) {
sqlException.printStackTrace();
System.out.println("Connection Error!");
}
String query="Insert into Identity values(0,'issam','issam#mail.com')";
try {
statement.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close() {
try {
connection.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
And the main class:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
DatabaseConnection connection= new DatabaseConnection("test.db");
connection.connect();
connection.close();
}
}
So I have this sqlite database but whenever I run the code it always gives me : Connection to "path" was successful, no matter what path I put...
I think I have done everything correctly, I downloaded the sqlite JDBC file and added it:
enter image description here
I tried adding a new row to a database table, but it always gives me this:
Connection to test.db successful
java.sql.SQLException: no such table: Identity
at org.sqlite.core.NativeDB.throwex(NativeDB.java:397)
at org.sqlite.core.NativeDB._exec(Native Method)
at org.sqlite.jdbc3.JDBC3Statement.executeUpdate(JDBC3Statement.java:116)
at com.issam.iamcore.DatabaseConnection.connect(DatabaseConnection.java:41)
at com.issam.iamcore.Main.main(Main.java:10)
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (Connection is closed)
at org.sqlite.core.DB.newSQLException(DB.java:890)
at org.sqlite.core.CoreStatement.internalClose(CoreStatement.java:109)
at org.sqlite.jdbc3.JDBC3Statement.close(JDBC3Statement.java:35)
at com.issam.iamcore.DatabaseConnection.close(DatabaseConnection.java:63)
at com.issam.iamcore.Main.main(Main.java:11)
Any help would be appreeciated, thanks !
You have successfully connected to the database, but did not create table Identity before executing insert query, as it says in the stack trace:
Connection to test.db successful
java.sql.SQLException: no such table: Identity
Call this before inserting a row:
String createQuery = "CREATE TABLE Identity (id INT PRIMARY KEY NOT NULL, name TEXT, email TEXT)";
statement.executeUpdate(createQuery);
I want to create a program to use it on any computer , so when i install it must import the database.sql from its place .. so i have to add it to the package of project , but when i did i have a message that's tells (java.sql.SQLException : no such table : table-name) , even though am sure that I have a table there.
so could u tell me where is the problem . or if there is any way to import the database from project folder wherever it was ?
thank you !
import java.awt.*;
import java.sql.*;
import javax.swing.*;
public class dbc {
Connection conn = null;
ResultSet rs = null ;
PreparedStatement pst = null ;
public static Connection ConnecrDb() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:Tab.sqlite");
return conn;
}catch (Exception e ){
JOptionPane.showMessageDialog(null, e)
return null;
}
}
}
and there is a file in the package called Tab.sqlite
Firstly: You should copy/create a database and collect the database location path then when you are try to get a connection, should put the database urlPath into DriverManager.getConnection(urlPath);
Also you can try:
public Connection DBConn() {
String connStr = "jdbc:sqlite:<location path>/myDB.db";
Connection conn = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(connStr);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (SQLException e) {
e.printStackTrace();
System.exit(2);
}
return conn;
}
I solved the problem , I should write this :
Connection conn = DriverManager.getConnection("jdbc:sqlite:/src/Tab.sqlite");
if I want to import the sql database from package of project I have to add /src/myDB.sqlite
thank you all :D
the last days I was trying to learn how to access mySQL databases via Java.
I am able to load the driver and get a connection to the database ( at least I think so, since I don't get an exception there..)
the code is:
import java.sql.*;
public class test
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("driver loaded...");
}
catch(ClassNotFoundException e){
System.out.println("Error in loading the driver..."+e);
System.exit(0);
}
try
{
Connection dbConnection= DriverManager.getConnection("jdbc:odbc:test","root","password");
System.out.println("Connection successful...");
Statement stmt = dbConntection.createStatement();
stmt.executeUpdate("create table Accounts ( name char(20) )");
}
catch(SQLException e)
{
System.out.println("database-ConnectionError: "+e);
System.exit(0);
}
}
}
When I execute it, it says:
driver loaded... Connection successful...
database-ConnectionError: java.sql.SQLException: [MySQL][ODBC 5.2(w) Driver][mysqld-5.5.31]No database selected
I really don't know the problem, because I thought the database is selected during the "getConnection" process....
I tried to select a database by adding this line:
stmt.executeUpdate("use test;");
after creating the Statement.
unfortunately it didn't work because I got another exception which said I should check on the syntax. I don't understand that either because in my commandline it works just fine...
I don't know if it is possible to use these type of commands via Java so if it isn't, please forgive my mistake.
I hope you can help me and I didn't miss the solution during my own search!
Already Thanks to all who reply and use their time on my problems!
ps. If I forgot to point out some important infos ( I don't think i did) please ask:)
edit: I also tried to create a new database during runtime
stmt.executeUpdate("CREATE DATABASE test;");
this actually works, but the database won't be selected either...
Before you can add a table, you first have to select a database.
you can create a new database with:
CREATE DATABASE database_name
you can connect to a specific database with:
String url = "jdbc:mysql://localhost/databasename";
String username = "test";
String password = "test";
Connection connection = DriverManager.getConnection(url, username, password);
Firstly, I am considering my answer to show you another better way for connection with MySQL Database, it's much easier and less nu-expected Exception(s).
You need to do some steps:
Download Connector/J and add it to your class path(if you are using an IDE there is add the .jar to the library, or there is many tuts on YouTube).
Create your database in your MySQL program.
See this example below example below I made for you demonstrates how to connect and execute queries on MySQL :
import java.sql.*;
public class MySqlConnection {
private String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
private String MYSQL_URL = "jdbc:mysql://localhost:3306/test";
private Connection con;
private Statement st;
private ResultSet rs;
public MySqlConnection() {
try {
Class.forName(MYSQL_DRIVER);
System.out.println("Class Loaded....");
con = DriverManager.getConnection(MYSQL_URL,"","");
System.out.println("Connected to the database....");
st = con.createStatement();
int c =st.executeUpdate("CREATE TABLE Accounts (Name VARCHAR(30))");
System.out.println("Table have been created.");
System.out.println(c+" Row(s) have been affected");
con.close();
} catch(ClassNotFoundException ex) {
System.out.println("ClassNotFoundException:\n"+ex.toString());
ex.printStackTrace();
} catch(SQLException ex) {
System.out.println("SQLException:\n"+ex.toString());
ex.printStackTrace();
}
}
public static void main(String...args) {
new MySqlConnection();
}
}
Here is your updated example, which works for me.
public static void main(String[] args) throws InstantiationException,
IllegalAccessException {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("driver loaded...");
} catch (ClassNotFoundException e) {
System.out.println("Error in loading the driver..." + e);
System.exit(0);
}
try {
Connection dbConnection = DriverManager
.getConnection("jdbc:mysql://localhost/test?user=root&password=password");
System.out.println("Connection successful...");
Statement stmt = dbConnection.createStatement();
stmt.executeUpdate("create table Accounts ( name char(20) )");
} catch (SQLException e) {
System.out.println("database-ConnectionError: " + e);
System.exit(0);
}
}
Make sure you have added a proper mysql-connector to your build path. I used the: mysql-connector-java-5.1.24-bin.jar
static final String DB_URL = "jdbc:mysql://localhost:3306/sys";
Use database name in the URL.
It worked for me
Does anyone know what the best way is to create a new oracle database connection. This is what I currently have:
private static getConnection() throws Exception {
if (!isDriverRegistered){
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
isDriverRegistered = true;
}
return DrvierManager.getConnection(connectionString);
}
You are not supposed to register the driver yourself; the JDBC driver itself will do that, when its class is loaded. So, do not call DriverManager.registerDriver yourself.
There are two steps: make sure the JDBC driver class is loaded, and get a connection.
To load the JDBC driver class, use a line like this:
Class.forName("oracle.jdbc.OracleDriver");
Then get the connection with a call to DriverManager.getConnection:
Connection conn = DriverManager.getConnection(connectionString);
Note that if you are using a newer JDBC version and a suitable driver, you do not even need to load the driver class explicitly; it will be found and loaded automatically (via Java's service discovery mechanism). In that case you only need to call DriverManager.getConnection.
this class may help you
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCHelper {
public static void close(Statement obj)
{
try
{
if(obj!=null)
obj.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet obj)
{
try
{
if(obj!=null)
obj.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public static void close(Connection obj)
{
try
{
if(obj!=null)
obj.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public static Connection getConnection()
{
Connection con = null;
String url = "url" //give url
String pwd = "password";//give password
String uid = "userId";//give userid
try
{
Class.forName("oracle.jdbc.OracleDriver"); //pass driver name
con = DriverManager.getConnection(url,uid,pwd);
con.setAutoCommit(false);
}
catch(Exception e)
{
if(con!=null)
try {
con.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
return con;
}
}