I have two local databases I'm trying to connect to using Java's Connection class. It's easy enough to connect to the first database using:
public Connection conn;
conn = DriverManager.getConnection(connectionString);
How can I add a second database to that same connection? They're both on the same server so it should be fairly simple but I can't find the right commands to do it.
Thanks
A Connection is a session with a specific database. You can't use one Connection to communicate with two different databases; for that, you need two separate Connections.
Connection conn1 = DriverManager.getConnection(connectionString1);
Connection conn2 = DriverManager.getConnection(connectionString2);
Have you tried:
public Connection conn1;
conn1 = DriverManager.getConnection(connectionString1);
public Connection conn2;
conn2 = DriverManager.getConnection(connectionString2);
Instance members shouldn't be public.
Connection should be a local variable, not an instance member.
You can only connect to one database at a time with a single Connection. Ergo you need another Connection.
I think you have to use J2EE, JTA transaction manager to accomplish this.
Related
If we had an instance of Connection con = DriverManager.getConnection (url) and call the getConnection method again with some other url, ie some url to another database, such as con = DriverManager.getConnection (secondUrl) do you need to close the previous one established connection or method "recognizes" that an established connection already exists and closes it itself?
DriverManager.getConnection() asks a new connection from the driver. It has no special knowledge of any other connections so it does not recognize anything. You can see all it does by looking at the source code. It's not much.
It would not make sense for it to close the previous connection. How would it know you're not using it anymore? It is perfectly valid to have several connections to a database active. That's what connection pools are meant for.
As an app programmer, one should also note that DriverManager is not used that much anymore for database connections, and its use is discouraged. Connection pooling and Datasources are.
I'm creating app for library management with Java and MySQL ( JDBC to connect with DB ) , and I have a problem , I checked a lot of topics, books, and websites but I didn't find good answer for me. Is it the good way to deal with connections ? I think that one connection for entire app is good option in this case. My idea is that in every function in every class when I need to use Connection object , these functions will need a connection parameter. In main class I'll call manager object 'Man' for example and to every constructor etc I'll pass Man.getMyConn() as this parameter and call Man.close() when Main frame will be closed . Is it bad idea ? Maybe I should use singleton pattern or connection pool ?
Sorry for my English , I'm still learning.
public class manager {
private Connection myConn;
public manager() throws Exception {
Properties props = new Properties();
props.load(new FileInputStream("app.properties"));
String user = props.getProperty("user");
String password = props.getProperty("password");
String dburl = props.getProperty("dburl");
myConn = DriverManager.getConnection(dburl, user, password);
System.out.println("DB connection successful to: " + dburl);
}
public Connection getMyConn() {
return myConn;
}
//close class etc.
}
Usually not. Further answer depends on type of the application. If you're making web application then you should definitely go with connection pool. If you're making e.g. desktop application (where only one user can access it at the time), then you can open and close connection upon each request.
I have working applications that do it your way. As #Branislav says, it's not adequate if you want to do multiple concurrent queries. There's also a danger that the connection to the database might be lost, and you would need to restart your application to get a new one, unless you write code to catch that and recreate the connection.
Using a singleton would be overcomplicated. Having a getConnection() method (as you have done) is very important as it means you can easily change your code to use a pool later if you find you need to.
I'm using singleton design-pattern for my database connection.
Here is my method.
private static Connection con=null;
public static Connection getConnection(){
try {
if(con==null){
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "");
}else if(con.isClosed()){
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "");
}
} catch (Exception ex) {
}
return con;
}
Whenever I restarted mysql service, it generates following error and have to restart the application also to run again.
Error:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
Can anyone show what is the correct way of implementing this to avoid this error?
thank you.
You're reusing the same Connection object across... well, everything. Your singleton should be a ConnectionFactory that returns a new connection every time.
As someone already noted, rather than create/close new connections use a connection pool. You don't have to write it yourself—there are readily available open-source implementations such as C3PO or DBCP.
Even better, rather than reinventing this wheel all over again, use a DataSource. If you can use Spring, it has a DriverManagerDataSource implementation just for this. Otherwise, feel free to look at how it's written and write your own (I've done this at least once when Spring wasn't an 'allowed' technology).
Finally, if you're running in a container such as Tomcat, JBoss or Glassfish, then you can simply bind a DataSource to JNDI and use that. This frees up your application from having to handle pooling and configuration/deployment issues (stuff like database user name & password) itself.
You should go for connection-pooling.
Your mechanism won't work if mysql server drops your connection some how.
I'm trying to make a connection pool following this link:
http://192.9.162.55/developer/onlineTraining/Programming/JDCBook/conpool.html
I don't understand something:
Somewhere in the class JDCConnectionDriver implements Driver you can find this method:
public static final String URL_PREFIX = "jdbc:jdc:";
public Connection connect(String url, Properties props)
throws SQLException {
if(!url.startsWith(URL_PREFIX) {
return null;
}
return pool.getConnection();
}
so, if you use mysql (for example), the url it will always start with jdbc... so the method connect it will never return you a connection...
Why is that?
Also I would like to ask you which is the best connection pooling framework...
so, if you use mysql (for example),
the url it will always start with
jdbc... so the method connect it will
never return you a connection... Why
is that?
This driver is specifically written to connect to a JDC Connection. That's why. It's looking for a url starting with jdbc:jdc: and not just jdbc:.
Also I would like to ask you which is
the best connection pooling
framework...
The most well known Connection Pooling library out there and used on many application servers and servlet containers is Apache Object Pool. The most common connection pooling is Apache DBCP (DataBase Connection Pooling).
Also, as stated by Rocky Triton, c3p0 is another JDBC library that included Connection and Statement Pooling.
I have create a getDBConnection method in my Java application. This returns a connection object, and hence I haven't closed this connection in this method itself.
Now, I am invoking this method from various methods in my application at regular intervals, and closing them inside a try - finally block. I thought this should free up the connection after use. However, I am seeing a large number of connections opened (about 50) in the MySQL Administrator's Server Connections tab.
//Defining a method to retrieve a database connection
// PropDemo is a properties class that retrieves Database related values from a file
public Connection getDBConnection() {
//Instantiating the Properties object
PropDemo prop = new PropDemo();
Connection con = null;
// Retrieving values from the parameters.properties file
String JdbcDriver = prop.getMessage("JdbcDriver");
String JdbcUrlPrefix = prop.getMessage("JdbcUrlPrefix");
String DBIP = prop.getMessage("DBIP");
String DBName = prop.getMessage("DBName");
String DBUser = prop.getMessage("DBUser");
String DBPassword = prop.getMessage("DBPassword");
try {
// Loading and instantiating the JDBC MySQL connector driver class
Class.forName(JdbcDriver).newInstance();
con = DriverManager.getConnection(JdbcUrlPrefix + DBIP + "/" + DBName, DBUser, DBPassword);
if (con.isClosed())
Logger.log("Connection cannot be established", "vm");
} catch (Exception e) {
Logger.log("Exception: " + e, "vm");
Logger.log(Logger.stack2string(e), "vm");
}
return con;
}
I am also closing the associated ResultSet and Statement Objects. What could be missing here?
I am planning to replace all the Statements with PreparedStatements for efficiency and security reasons. Will that help significantly? What else can be done?
EDIT:
This is just a core java application that is repeatedly quering for changes in some fields in a MySQL database through MySQL-JDBC connector. I am not using any framework like Spring or Hibernate.
Your code looks sane.
That's how you're creating a new connection.
Probably the error is where you close it.
You should close it in a finally block.
Some additional questions.
1) Are you sure those 50 conections come from this program ? Maybe there are some others comming from your same office. To confirm this you would need to stop the program, and look again in your connection monitor.
2) Does your application uses many connection simultaneously? Probably its a peak when you're using 50 at the same time.
If you can post the code where you close the connection. Chances are the problem is there.
Additionally I would suggest you to use a connection pool. You can build one your self or you can see the results from this page:
How many JDBC connections in Java?
Are you closing the connection object when you application closes as well?
Are you using your JDBC connection within a J2EE application server or with Hibernate?
Both of these tend to start out with a fairly high connection pool to begin with, so you would see a large number.
Check out the details on connection pooling.
You could take a Singleton approach to the problem and only create a new Connection object if the current one is null:
If (connectionObject != null){
return connectionObject;
}else {
//create new connection object
}
This will make sure that you only have one non-null connection at any time.