How can I store my connection string eg: "jdbc:oracle:thin:@local:testserver","scott","tiger" in a String variable and pass that string to the connection?
3 Answers
what about
String connString = "jdbc:oracle:thin:@local:testserver";
pass that in to your connection:
Connection conn = DriverManager.getConnection(connString,"someUsername","somePassword");
Theres a tutorial on how to connect to oracle databases with Java here
Thin name service syntax: http://docs.oracle.com/cd/B28359_01/java.111/b31224/urls.htm#BEIDHCBA
If you need to supply other Oracle-specific connection properties then you need to use the long TNSNAMES style. The TNS format is:
jdbc:oracle:thin:@(description=(address=(host=HOSTNAME)(protocol=tcp)(port=PORT))(connect_data=(service_name=SERVICENAME)(server=SHARED)))
Comments
You can istantiate a String like this:
String connectionString = "jdbc:oracle:thin:@local:server";
and then use this String for connection, like Thousand wrote.
Anyway, I think that this code can't be reusable. It should be better to create a class connection like this:
import java.sql.Connection;
import java.sql.DriverManager;
public class ConectionTest {
static Connection getConnection() throws Exception {
String connectionString = "jdbc:oracle:thin:@local:server";
String driver = "com.mysql.jdbc.Driver";
String userName = "usertest";
String password = "pwdtest";
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(connectionString, userName,password);
return conn;
}
}
And then use the connection anywhere.