How to connect two database through JDBC? Is it possible? - java

I have tried to connect the mysql database with the frontend with the help of JDBC driver. But i dont know how acna we implement connectivity to connect the two different databases with each other with the help of JDBC driver.

You can create two connections. One for the first database and the other for the second database. You can send commands to the first database using the first connection and you can send commands to the second database using the second connection. Your application will serve the purpose of connecting the two databases as you can select rows from one database, parse them and insert the resulting records into the other.

There is no magic in JDBC that allows you to 'connect the two database with each other'. You need to code this yourself. You create two connections, one for each database and then you write the queries and transformations to get your data from database 1 to database 2.
try (
Connection connectionToDb1 = DriverManager.getConnection(
"jdbc:firebirdsql://serverA/database1", "username", "password");
Connection connectionToDb2 = DriverManager.getConnection(
"jdbc:firebirdsql://serverB/database2", "username", "password");
Statement selectFrom1 = connectionToDb1.createStatement();
ResultSet rsFrom1 = selectFrom1.executeQuery(
"SELECT columnA, columnB FROM tableX");
PreparedStatement insertTo2 = connectionToDb2.prepareStatement(
"INSERT INTO tableY(column1, column2) VALUES (?, ?)");
) {
while (rsFrom1.next()) {
insertTo2.setString(1, rsFrom1.getString("columnA"));
insertTo2.setString(2, rsFrom1.getString("columnB"));
insertTo2.executeUpdate();
}
}
Note that this isn't a complete example: for production purposes you would disable auto commit, and use batch updates.
There are tools that can do this for you, but tool and library suggestions are off topic on SO, but I'd suggest you search for ETL (or extract, transform, load), or maybe for datapump.

Related

Correct design for querying DB through out the app

I want to use sqlite driver for my java application that I am developing with netbeans. What would be the correct "design" when it comes to integrating DB queries?
Basically should I create a static variable holding the connection which I can use to execute SQL statements through out the app? Or should I create the connection everytime I want to do the query?
Here is my code
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:Mydb.db");
st = conn.createStatement();
rs = st.executeQuery(/*My sql statement*/);
Thank you
Creating connection every time you write a query is not a good approach because it will be an overload on database for handling multiple connections.
Rather you should prefer a method or a class which would return you an instance of database connectivity.

Java Connection String to query from two database

I am having a problem. I have a query that checks one database table and updates another database table. I am using MySQL 5.1
UPDATE dldd.temp,test.temp
SET test.temp.name = dldd.temp.word
WHERE dldd.temp.id = test.temp.id
this is my SQL statement that is working fine. Now I want to execute this statement using Java PreparedStatement . The problem is I don't know how to write the Connection String to select two database i.e
"jdbc:mysql://localhost:3306/"+dbname+"?characterEncoding=UTF-8"
What should come in place of dbname. Can I select multiple db there.
Have a look at http://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html.
If the database is not specified, the connection is made with no default database. In this case, either call the setCatalog() method on the Connection instance, or fully specify table names using the database name (that is, SELECT dbname.tablename.colname FROM dbname.tablename...) in your SQL. Opening a connection without specifying the database to use is generally only useful when building tools that work with multiple databases, such as GUI database managers.

how can i retrieve data from multiple databases in a single query?

if i have multiple database with same Tables and Columns how can i retrieve Data from those Databases using single Query in Java.
Done this for single Database, i am newbie in java, please suggest.
public class MultipleDBTest{
public void dbConnect(String db_connect_string, String db_userid, String db_password){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select <Col1>, <Col2> from <Table>";
ResultSet rs = statement.executeQuery(queryString);
while(rs.next()){
System.out.println(rs.getString(1) + " | " + rs.getString(2));
}
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://localhost;databaseName=<Database1>","<Username>","<Password>");
}
}
The easiest way to get data from multiple servers is linking them, querying the data from each table using the fully qualified table name, i.e. Server.Database.Schema.Table, and make the union of all.
Yo can only specify the desired server in the fully qualified name, Server, if you link the other servers to the server where you're making the query.
You'd end up with something like this
select * from Server1.Database1.dbo.Table
union
select * from Server2.Database2.dbo.Table
union
select * from Server3.Database2.dbo.Table
Please, see this article to understand what are linked servers and how you set them up: Linked Servers (Database Engine).
Let Sql Server do the work for you. Create a view in one of the databases that references the data from the tables in the other databases. That way your code need only access one object in one database, the view.
This is easiest if the databases are on the same server. If the databases are on separate servers you will need to link them.
If by "multiple databases" - you mean multiple schemas in the same database, then you can use the schema name and make the JOIN. Also, ensure that you have sufficient privileges to read both the schemas. SQL query would be of the form:
select S1T1.Col1, S1T1.Col2, S2T1.Col1, S2T1.Col2
from Schema1.T1 S1T1, Schema2.T1 S2T1
where S1T1.Col1=S2T1.Col1
And if you mean multiple databases on different database instances, then you may have to create links between the database instances. Refer to this SO post for more information:
Querying data by joining two tables in two database on different servers
If the information helps, don't forget to vote. Thanks! :)
Database.Schema.Table when referencing tables
and
Database.Schema.Table.Column when referencing columns
You can write joins between databases this way and deffinately pull data from more than one database.
USE [DatabaseA]
SELECT * FROM DatabaseA.dbo.DSNA_tblMaiin
INNER JOIN DatabaseB.dbo.DSNB_tblMaiin ON DatabaseA.dbo.DSNA_tblMaiin.Serialnumber = DatabaseB.dbo.DSNB_tblMaiin.Serialnumber
INNER JOIN DatabaseB.dbo.DSNC_tblMaiin ON DatabaseA.dbo.DSNA_tblMaiin.Serialnumber = DatabaseC.dbo.DSNC_tblMaiin.Serialnumber
What you are looking for is the federation layer. the layer will parse the SQL, Queries per DB will be created. Those independent queries will get fired on DB and result will be joined based on where clause. There are some Antlr based SQL Grammars available on the net, so you use them for parsing the SQL and generating DB specific SQLs.

How to connect to remote database through DB link using JDBC?

I need to connect to a remote database using Database link using JDBC commands.
How can it be done?
If you already have the dblink setup, you can utilize it in your SQL (sent via jdbc) by addressing the required tables like such:
select * from SCHEMA.TABLE#DBLINK_NAME
Using this query inside of your java would look something like this
public ResultSet execQuery() throws SQLException, ClassNotFoundException{
//Load the database driver
Class.forName("oracle.jdbc.OracleDriver");
//Create connection to the database
Connection myConnection = DriverManager.getConnection(connectURL,userName,userPwd);
//Create a statement link to the database for running queries
Statement myQuery = myConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
//Create a resultSet to hold the returned query information
ResultSet myQueryResults = myQuery.executeQuery("select * from SCHEMA.TABLE#DBLINK_NAME");
return myQueryResults;
}
*java & oracle assumed
If you are asking about how to use JDBC to create a link between the DB you are talking to and another one, then it is "just SQL" that you (presumably) would execute in the same way as you would any other SQL statement. (If you tell us which DB you are using, we could talk about the actual SQL you need to execute.)
Otherwise, I don't think this makes sense. A DB link / Database link is a link from one database to another. But JDBC is for talking to a database from a Java client. It makes no sense (to me) to use DB link to connect a JDBC client to a database.
Please take a look at orajdbclink, on sourceforge
I am planning to to connect my oracle plsql sources to phoenix skin of hbase. It seems to me the unique way to create a connector between oracle and hbase for the moment...

Is it possible create new account in MySQL from Java?

I need use SQL without working with MySQL. Just from Java create account, databases, export and import databases. Its possible? Or I should prefer XML for it?
you can of course do it via a Statement that executes the MySQL commands for creating users:
Connection con = ...; //initialize your mysql connection
Statement s = con.createStatement();
s.execute( "CREATE USER ... " );
See the mysql page here for the syntax of create user statement.

Categories