How can I insert data from a connection to other connection? - java

I want to insert data from a table which connection is oracle to another table which connection is mysql. I use netbeans and jdbc driver.
Is it possible? I mean how can I do select data from A table (X connection) and insert B table (Y connection)
connection X = DriverManager.getConnection("jdbc:oracle:thin:#" + host__ + ":" + port__ + servic, props);
connection Y = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
conn.close();
Thank you.

Here is a small example that copies a database table to another database.
You just need two connections conf(rom) and cont(o). You will need to modify both getConnection parameters, table names and field types.
// Copy
Statement stf, stmt;
Connection conf, cont;
ResultSet rsf, rs;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("com.mysql.jdbc.Driver");
conf = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:" + databaseFrom, "user1", "passwd1");
try {
stf = conf.createStatement();
rsf = stf.executeQuery("select * from supplier order by sname");
// read from rsf write to rs!
cont = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + databaseTo, "user2", "passwd2");
stmt = cont.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("select * from supplier order by sname");
while (rsf.next()) {
rs.moveToInsertRow();
rs.updateInt(1, rsf.getInt(1));
rs.updateString(2, rsf.getString(2));
rs.updateString(3, rsf.getString(3));
rs.updateString(4, rsf.getString(4));
rs.updateInt(5, rsf.getInt(5));
rs.updateString(6, rsf.getString(6));
rs.updateInt(7, rsf.getInt(7));
rs.updateDouble(8, rsf.getDouble(8));
rs.updateString(9, rsf.getString(9));
rs.insertRow();
}
} catch (SQLException s) {
JOptionPane.showMessageDialog(this, "problem creating database " + s);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getStackTrace());
} finally {
if (stf != null) {
try {
stf.close();
stmt.close();
} catch (SQLException e) {
// handle Exception
}
}
if (conf != null) {
try {
conf.close();
cont.close();
} catch (SQLException e) {
// handle Exception
}
}
}

You can create two classes for different connection:
public class OracleConnectionManager {
public static Connection getOracleConnection() throws SQLException, ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = null;
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:oracle","username","password");
return connection;
}
}
public class MySqlConnectionManager {
public static Connection getMySqlConnection() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = null;
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306:mysql","username","password");
return connection;
}
}
Now you can use these classes to get the specific connections and do whatever you want.
You can get the oracle database connection and get the oracle statement > Resultsset, iterate over it
and insert the data into mysql.
Please let me know in case more information is required.

Follow these steps:
Connect to the Oracle database with one data access class
Connect to the MySQL database with a different data access class
Read row(s) from a table in the Oracle database
Perform any column transformations
Write row(s) to a table in the MySQL database
Close the database connections

Related

JDBC / MySQL: How to check if a database or relation exists when creating one, then print off an error if it does

I'm VERY new to JDBC and am trying to work on a project for a class. We are supposed to create a database and relations for said database. If the database or relations already exist, we are supposed to print a message notifying the user. I'm not really sure how to do that. This is what I have so far for my methods:
public static void createDatabase() throws Exception {
String createString =
"CREATE DATABASE IF NOT EXISTS companydb";
Statement stmt = null;
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/?autoReconnect=true&useSSL=false";
String username = "username";
String password = "password";
Class.forName(driver);
Connection con = DriverManager.getConnection(url, username, password);
stmt = con.createStatement();
stmt.executeUpdate(createString);
System.out.println("Database created.");
} catch (Exception e) {
System.out.println(e);
} finally {
if (stmt != null) { stmt.close();
}
}
}
And for creating an employee table (not all values are created yet, just a test run):
public static void createEmployeeTable() throws Exception {
String createString =
"create table if not exists employee" + "(Fname char(32) NOT NULL, " +
PRIMARY KEY(Fname)";
Statement stmt = null;
try {
Connection con = getConnection();
stmt = con.createStatement();
stmt.executeUpdate(createString);
System.out.println("Employee table created.");
} catch (Exception e) {
System.out.println(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}
Also I realize creating a table like that might not be the most efficient way to make a relation, but it's just a work in progress right now. Thanks for any help anyone can provide!
Regardless of if the database and relations/tables already exist or not, it puts out the same output:
Database created.
Connected to database.
Employee table created.
Connected to database.
Department table created.
Connected to database.
Project table created.
Connected to database.
Works_On table created.
Break down your code to two steps.
Execute a select query on the table. If the table does not exist, this will definitely throw an error.
If the select does not throw an error you can go ahead and create the table.

cannot exexute SQL query wirh OJDBC and Oracle DB (but full working with posgtres JDBC and Postgres DB)

I wrote a java program which retrieve data from a PG gb, process them, and write them in an Oracle DB.
While the PG part is fully working, the Oracle one has issues.
I can connect to the DB, but every query ends with a rollback (ResultSet with Oracle is always null)
Of course i have both PG and Oracle JDBC driver.
Here are my DBs object and testing queries
private final static PostgresDB postgres = new PostgresDB("jdbc:postgresql://192.168.2.23:5432/T18CLEAN", "myPGUser", "myPGPasswd", true);
private final static OracleDB oracle = new OracleDB("jdbc:oracle:thin:#192.168.2.20:1521/EFFEVI.T18FV.IT", "myOracleUser", "myOraclePasswd");
private final static String testPostgres = "SELECT product_pricelist_item.x_product_name FROM public.product_pricelist_item;";
private final static String testOracle = "SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI;";
Then I setup the 2 connections:
PG:
public Connection getConnect() throws ClassNotFoundException {
System.out.println("-------- Posgres JDBC Connection Testing ------");
String url = c_url;
Connection conn = null;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", passwd);
props.setProperty("ssl", boolToString(sslEnabled));
try{
Class.forName("org.postgresql.Driver");
System.out.println("Postgres JDBC Driver Registered!");
} catch(ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return null;
}
try {
conn = DriverManager.getConnection(url, props);
System.out.println("You made it, take control your Postgres database now!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Failed to make connection to Postgres DB!");
}
return conn;
}
Oracle:
public Connection getConnect(){
Connection connection = null;
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return connection;
}
System.out.println("Oracle JDBC Driver Registered!");
try {
connection = DriverManager.getConnection(c_url, user, passwd);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return connection;
}
if (connection != null) {
System.out.println("You made it, take control your Oracle database now!");
return connection;
} else {
System.out.println("Failed to make connection to Oracle DB!");
}
return connection;
}
After all these pass i perform queries
public ResultSet executeCommand(Connection c, String command) {
Statement st = null;
ResultSet rs = null;
try {
st = c.createStatement();
rs = st.executeQuery(command);
} catch (SQLException e) {
}
if(rs==null){
System.out.println("Failed to Execute command " + command);
} else {
System.out.println("Command Executed: " + command);
}
return rs;
}
Assuming that there are no parameters error... What could it be? Any help?
Thank you very much
Remove a semicolon at the end of the query.
Use this:
private final static String testOracle =
"SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI";
instead of this one:
private final static String testOracle =
"SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI;";
Also don't silently "swallow" an exception in your code:
} catch (SQLException e) {
}
Rethrow the exception, or at least print the error to the log:
} catch (SQLException e) {
log.error("Error while executing query " + command, e);
throw new RuntimeException("Error while executing query " + command, e);
}

SQL, JDBC "Invalid column index" error with simple query

I'm new to STRUTS and JDBC, my application tries to connect to a simple DB that has 3 tables, right now all is doing is trying to query 1 table that only stores "first, last names and a Id field"
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return null;
}
System.out.println("Oracle JDBC Driver Registered!");
try {
connection =
DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","david","changeit");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return null;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
where I would like to get the result of 1 column if a match occurs:
String sql = "SELECT S_ID FROM Students WHERE firstname=? AND lastname=?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, firstname);
ps.setString(2, lastname);
rs = ps.executeQuery();
while (rs.next()) {
studentid = rs.getString(1);
ret = SUCCESS;
}
} catch (Exception e) { ...
As far as I can tell the connection is made,
the SQL query
Select s_id from Students where firstname='first' and lastname='last';
when run on SQL Dev. works and gives me a single result.
I don't really get a stack trace the code just jumps from right before the 'while (rs.next()) {..' directly into the finally block
} catch (Exception e) {
e.printStackTrace();
ret = ERROR;
} finally {
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
}
}
}
I'm not sure how Oracle drivers work. But below statement is what i see on Oracle site. Are you getting a non empty resultset ?
As you are not getting a nullpointerexception on .next(), i'm wondering if Oracle drivers return an empty ResultSet, which may lead to this problem.
http://docs.oracle.com/cd/B28359_01/java.111/b31224/getsta.htm
In case of a standard JDBC driver, if the SQL string being executed
does not return a ResultSet object, then the executeQuery method
throws a SQLException exception. In case of an Oracle JDBC driver, the
executeQuery method does not throw a SQLException exception even if
the SQL string being executed does not return a ResultSet object.
Like I said I'm new at using this.
The problem was that my schema didn't have the CONNECT role assigned to it.
Solution log in as 'SYSTEM' and grant the role to my schema
grant connect to MY_SCHEMA;

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'

Class not found loading JDBC org.postgresql.Driver

I'm working on a web project and I recently installed postgres 9.1.1
The postgresql server is up and running. I can connect via psql as usual and everything is loaded and properly saved from a dump of the db I made from 8.5.
So I also downloaded the JDBC4 driver for 9.1 postgres version here:
http://jdbc.postgresql.org/download/postgresql-jdbc-9.1-901.src.tar.gz
I added it to the java build path using the project properties via eclipse.
This is the code I use to provide db connection to other classes (i.e. it's a singleton, I get a new connection only if the existing is either closed or null, from one object at a time only)
public abstract class DBConnection {
private static Connection connection = null;
public static void connect() {
try {
if (connection == null) {
String host = "127.0.0.1";
String database = "xxxxx";
String username = "xxxxx";
String password = "xxxxx";
String url = "jdbc:postgresql://" + host + "/" + database;
String driverJDBC = "org.postgresql.Driver";
Class.forName(driverJDBC);
connection = DriverManager.getConnection(url, username,
password); //line firing the class not found exception
} else if (connection.isClosed()) {
connection = null;
connect();
}
} catch (SQLException e) {
e.printStackTrace(System.err);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public static void disconnect() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(
Level.SEVERE, null, e);
}
}
}
public static Connection getConnection() {
try {
if (connection != null && !connection.isClosed()) {
return connection;
} else {
connect();
return connection;
}
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE,
null, e);
return null;
}
}
#Override
public void finalize() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(
Level.SEVERE, null, e);
}
}
}
}
As I wrote in the title when I run the project and a class asks for a connection to this class I always get a Class Not Found Exception, Since it apparently can't load the org.postgresql.Driver.class The driver is located in a subfolder of the project ~/lib/org.postgresql-9.1-901.jdbc4.jar and as I said added to the build path via eclipse project properties.
I'm also providing a sample query to let see the usual behavior of my classes to access the DBConnection:
public static final User validateUserCredentials(String id, String pswd) {
Connection connection = DBConnection.getConnection();
Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE, (connection!=null)?"connection not null":"connection null");
Statement stmt = null;
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, "validating credentials for user: username : " + id + " password : " + pswd);
String sql = "Select * from fuser where id = '" + id + "'";
ResultSet resultset = null;
try {
stmt = connection.createStatement();
resultset = stmt.executeQuery(sql);
Logger.getLogger(Credentials.class.getName())
.log(Level.SEVERE, sql);
resultset.next();
String password = resultset.getString("pswd");
if (pswd.equals(password))
return new User(id, pswd);
} catch (SQLException ex) {
Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE,
null, ex);
} finally {
if (stmt != null)
stmt = null;
if (resultset != null)
resultset = null;
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
}
connection = null;
}
}
return null;
}
I'm working on a web project and I recently installed postgres 9.1.1
...
I added it to the java build path using the project properties via eclipse.
That's the wrong way. That JAR has to be dropped straight in /WEB-INF/lib folder of the web project without fiddling with the Build Path in the project's properties. That folder is standard part of webapp's runtime classpath.
Unrelated to the concrete problem: you've a major design flaw in your DBConnection class. You've declared Connection as static which essentially makes your connection not threadsafe. Use a connection pool and never assign the Connection (nor Statement nor ResultSet) as a class/instance variable. They should be created and closed in the very same try-finally block as where you're executing the query. Further you've there also a SQL injection hole. Use PreparedStatement instead of concatenating user-controlled variables in the SQL string.
See also:
JDBC MySql connection pooling practices to avoid exhausted connection pool
Get database connection from a connection pool
Am I Using JDBC Connection Pooling?
Add this dependency in your pom:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1203-jdbc4</version>
</dependency>
The first thing I'd do is unpack the jar and confirm that the driver is really in there as org.postgresql.Driver. I notice when looking at jarfinder and related sites that there isn't a Postgres 9.x jar containing org.postgresql.Driver.

Categories