Can anybody explain me these classes and methods?
DriverManager.registerDriver
(new oracle.jdbc.driver.OracleDriver());
conn = java.sql.DriverManager.getConnection(
"jdb:ocracle:thin:username/password#machine.us.company.com:1234:dbSID");
Thanks
Let's decode the lines of your code block:
1. DriverManager.registerDriver
2. (new oracle.jdbc.driver.OracleDriver());
3. conn = java.sql.DriverManager.getConnection(
4. "jdbc:oracle:thin:username/password#machine.us.company.com:1234:dbSID");
Line 2:
Creates a new instance of oracle.jdbc.driver.OracleDriver, a JDBC Driver for the Oracle database. A JDBC driver implements the interfaces and classes defined by the JDBC API that programmers use to connect to a database and perform queries.
Line 1
Registers the instance of the oracle.jdbc.driver.OracleDriver to the DriverManager class which is the traditional management layer of JDBC, working between the user and the drivers. It handles establishing a connection between a database and the appropriate driver.
Line 3:
Now that the communication layer between the JDBC application and the database is ready, you can create a connection by calling getConnection() method of the DriverManager class.
Line 4:
This is the "connection string" or "database URL". This String identifies the database you want to connect to. The scheme of this URL is specific to the database provider and/or the driver (here, Oracle and its "thin" driver).
Note that prior to Java 6, calling Class.forName was the preferred way to load and register a JDBC Driver. It was the responsibility of the Driver to call DriverManager.registerDriver.
[...] All Driver classes should be written with a static section (a static initializer) that creates an instance of the class and then registers it with the DriverManager class when it is loaded. Thus, a user would not normally call DriverManager.registerDriver directly; it should be called automatically by a Driver class when it is loaded.
Check the Driver Manager chapter from the JDBC documentation for more details.
This is JDBC which is the way Java programs talk to a database, and your sample explicitly asks for the Oracle driver which requires their driver in your classpath.
Sun has a good tutorial on the matter at http://java.sun.com/docs/books/tutorial/jdbc/overview/index.html
The DriverManager class in java handles the connections between the database and the jdbc drivers, routing db i/o to the correct jdbc driver (you can have multiple drivers active ie connections to multiple types of database).
Drivers are registered with the DriverManager so that they become part of its working set. The next step is to create a connection to your database, so you can run queries. This is achived by the
Connection conn = DriverManager.getConnection("jdb:ocracle:thin:username/password#machine.us.company.com:1234:dbSID")
method. The connection String passed into the getConnection() method is driver-specific, you need to RTFM for each driver. Note that the DriverManager selects the driver automatically from its list of registered drivers, according to the syntax of the connection string you pass in.
The Connection object returned is your handle for preparing statements and running queries against the database
Related
I have a java application which is able create a connection to multiple DB.
We are loading these drivers:
Class.forName("org.mariadb.jdbc.Driver");
Class.forName("com.treasure_data.jdbc.TreasureDataDriver");
When I try to connect to aurora DB I would expect DriverManager to use the MariaDB driver - but instead it is using treasure_data driver.
java.sql.Connection conn1 = DriverManager.getConnection("jdbc:mysql:aurora://YYY-aurora.XXXXX.com:3306/SomeDBName", "USER", "PASSWORD");
and this is the error I get:
java.sql.SQLException: Invalid JDBC URL: jdbc:mysql:aurora://YYY-aurora.XXXXX.com:3306/SomeDBName. URL prefix must be jdbc:td://
Why is DriverManager using the treasure_data Driver?
The java.sql.DriverManager will ask each registered driver to create a connection with the JDBC url until one driver either returns a (non-null) java.sql.Connection or throws an SQLException.
From JDBC 4.2 section 9.2 The Driver interface:
When the DriverManager is trying to establish a connection, it calls that driver's connect method and passes the driver the URL. If the Driver implementation understands the URL, it will return a Connection object or throw a SQLException if a connection cannot be maded to the database. If the Driver implementation does not understand the URL, it will return null.
From the Driver.connect API doc:
Attempts to make a database connection to the given URL. The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given URL. This will be common, as when the JDBC driver manager is asked to connect to a given URL it passes the URL to each loaded driver in turn.
The driver should throw an SQLException if it is the right driver to connect to the given URL but has trouble connecting to the database.
So a compliant JDBC driver must return null when it is asked to create connection for a JDBC URL it doesn't recognize/support. Only when the URL is supported (eg because the prefix matches the driver), is a driver allowed to throw an SQLException (eg when there is a syntax error in the rest of the JDBC URL, or if the connection cannot be established).
So the com.treasure_data.jdbc.TreasureDataDriver is misbehaving because it throws an SQLException for an URL it doesn't recognise; you need to file a bug report with the author of that driver.
My server app uses prepared statements in almost all cases, to prevent sql injection. Nevertheless a possibility is needed providing special users executing raw SELECT queries.
How can I more or less securely make sure the query does not modify the database? Is it possible to execute a query read only, or is there any other 'secure' way making sure noone tries any sql injection?
(Using sqlite3, so I cannot use any privileges)
Thanks a lot!
JDBC supports read-only connections by calling Connection.setReadOnly(true). However the javadoc says:
Puts this connection in read-only mode as a hint to the driver to enable database optimizations.
Some JDBC drivers will enforce the read-only request, others will use it for optimizations only, or simply ignore it. I don't know how sqlite3 implements it. You'll have to test that.
Otherwise, you could do a "simple" parse of the SQL statement, to ensure that it's a single valid SELECT statement.
I'm not aware of a general JBDC configuration which specifies readonly. But Sqlite does have special database open modes and this can be leveraged in your connection to your sqlite database. Eg.
Properties config = new Properties();
config.setProperty("open_mode", "1"); //1 == readonly
Connection conn = DriverManager.getConnection("jdbc:sqlite:sample.db", config);
Credit: https://stackoverflow.com/a/18092761/62344
FWIW All supported open modes can be seen here.
If you use some sort of factory class to create or return connections to the database, you can individually set connections to be read-only:
public Connection getReadOnlyConnection() {
// Alternatively this could come from a connection pool:
final Connection conn = DriverManager.getConnection("jdbc:sqlite:sample.db");
conn.setReadOnly(true);
return conn;
}
If you're using a connection pool, then you may also want to provide a method for getting writeable connections too:
public Connection getWriteableConnection() {
final Connection conn = getPooledConnection(); // I'm assuming this method exists!
conn.setReadOnly(false);
return conn;
}
You could also provide just a single getConnection(boolean readOnly) method and simply pass the parameter through to the setReadOnly(boolean) call. I prefer the separate methods personally, as it makes your intent much clearer.
Alternatively, some databases like Oracle provide a read only mode that can be enabled. SQLite doesn't provide one, but you can emulate it by simply setting the actual database files (including directories) to read only on the filesystem itself.
Another way of doing it is as follows (credit goes to deadlock for the below code):
public Connection getReadOnlyConnection() {
SQLiteConfig config = new SQLiteConfig();
config.setReadOnly(true);
Connection conn = DriverManager.getConnection("jdbc:sqlite:sample.db",
config.toProperties());
}
I'm following the JDBC Developer's Guide and trying to test the JDBC thin driver connection using a short java program.
import java.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.OracleDataSource;
class JDBCVersion
{
public static void main (String args[]) throws SQLException
{
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:hr/hr#localhost:1522:orcl");
Connection conn = ods.getConnection();
// Create Oracle DatabaseMetaData object
DatabaseMetaData meta = conn.getMetaData();
// gets driver info:
System.out.println("JDBC driver version is " + meta.getDriverVersion());
}
} //<host>:<port>:<service>
I've tried every possible <host>:<port>:<service> combination but still get a java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
I've successfully tested the OCI driver using another program included in the tutorial....but can't get this one to work. My application will be using the thin driver to connect to the database so my frustration level is....climbing.
Any help is appreciated.
Maybe following comments could explain why you need the sevice name instead of the SID in the URL.
the Oracle JDBC FAQ mention that SIDs will be cease to be supported in one of the next few releases of the database
the Oracle JDBC devolopers guide mention Always connect to a service. Never use instance_name or SID because these do not direct to known good instances and SID is deprecated
the Oracle 2 day + Java developer tutorial mention the syntax jdbc:oracle:driver_type:[username/password]#//host_name:port_number:SID which seems to be a mixture of SID and service name URL (following the other documents and your working example)
in contrast the javadoc for OracleDriver mention only the SID syntax
the Oracle FAQ wiki mention both syntax
.
jdbc:oracle:thin:[USER/PASSWORD]#[HOST][:PORT]:SID
jdbc:oracle:thin:[USER/PASSWORD]#//[HOST][:PORT]/SERVICE
I'm able to connect to my container DB (containing my tables, packages, etc.) using the username/password.
Returns:
JDBC driver version is 12.1.0.2.0
Still can't connect to the tutorial "HR" PDB that comes with the oracle 12c install and which the JDBC tutorial uses.
Edit:
Got it to work using the following:
import java.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.OracleDataSource;
class JDBCVersion
{
public static void main (String args[]) throws SQLException
{
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:#//localhost:1522/pdborcl.global.XXXXXXXX.com");
ods.setUser("hr");
ods.setPassword("hr");
Connection conn = ods.getConnection();
// Create Oracle DatabaseMetaData object
DatabaseMetaData meta = conn.getMetaData();
// gets driver info:
System.out.println("JDBC driver version is " + meta.getDriverVersion());
}
}
Still don't understand why I need the full global name instead of the instance name.
When connecting to a PDB you should always use the PDB's service name in the connection string. It looks like your PDB's service is "pdborcl.global.XXXXXXXX.com" so that's what you need to use to connect the PDB directly.
Personally I find it easier to use the long URL format:
"jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1522))(CONNECT_DATA=(SERVICE_NAME=pdborcl.global.XXXXXXXX.com)))"
It makes it obvious that you're using a Service name instead of an SID.
The beauty of it is that you can also easily test your connection string with sqlplus:
sqlplus "hr/hr#(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1522))(CONNECT_DATA=(SERVICE_NAME=pdborcl.global.XXXXXXXX.com)))"
If sqlplus works there is not reason why the JDBC Thin driver wouldn't.
Finally you can also connect the root database using a privilege user and then execute "ALTER SESSION SET CONTAINER=pdb" to switch to the PDB. Should you decide to do so you would have to modify your connection string to connect to the root container first. It should have its own service name.
I have a Solid Database. And I want to connect to this DB by JDBC. How can I get URL for connection creation?
[EDIT]
For more information:
SOLID JDBC Driver
Programmer's Guide
SOLID JDBC Driver 2.3 Readme
Registering JDBC Driver
The JDBC driver manager, which is written entirely in Java, handles loading and unloading drivers and interfacing connection requests with the appropriate driver. It was JavaSoft's intention to make the use of a specific JDBC driver as transparent as possible to the programmer and user.
The driver can be registered with the three alternative ways, which are shown below. The parameter required by Class.forName and Properties.put functions is the name of the driver, which is solid.jdbc.SolidDriver.
// registration using Class.forName service
Driver)Class.forName("solid.jdbc.SolidDriver")
// a workaround to a bug in some JDK1.1 implementations
Driver d = (Driver)Class.forName("solid.jdbc.SolidDriver").newInstance();
// Registration using system properties variable also
Properties p = System.getProperties();
p.put("jdbc.drivers", "solid.jdbc.SolidDriver");
System.setProperties(p);
Connecting to the database
Once the driver is succesfully registered with the driver manager a connection is established by creating a Java Connection object with the following code. The parameter required by the DriverManager.getConnection function is the JDBC connection string.
Connection conn = null;
try {
conn = DriverManager.getConnection(sCon);
}
catch (Exception e) {
System.out.println("Connect failed : " + e.getMessage());
throw new Exception("Halted.");
}
The connect string structure is jdbc:solid://://. The string "jdbc:solid://fb9:1314/dba/dba" attempts to connect a SOLID Server in machine fb9 listening tcp/ip protocol at port 1314.
The application can establish several Connection objects to database. Connections can be closed be the following code.
conn.close();
I just want to make sure that if I use the following, I am opening a separate DB session and not resuing the same one (for testing I need individual sessions).
Connection connection = DriverManager.getConnection(URL,USER,PASSWORD);
each time I do the above code, I run my query, then do a connection.close()
So for example:
while(some condition) {
Connection connection = DriverManager.getConnection(URL,USER,PASSWORD);
//now use the connection to generate a ResultSet of some query
connection.close();
}
So, each iteration of the loop (each query) needs its own session.
Is this properly opening separte sessions as I need (and if not, what would I need to add/change)? thanks
The javadoc says:
Attempts to establish a connection to
the given database URL
Slightly woolly language, and I suspect that this is up to the JDBC driver, but I'd be surprised if this did anything other than open a new connection.
I suppose it's possible for a JDBC driver to perform connection pooling under the hood, but I'd be surprised to see that.
In the case of the Oracle JDBC driver, this will open a new connection every time. This is a relatively slow process in Oracle, you may want to consider using a connection pool (e.g. Apache Commons DBCP, or c3p0) to improve performance.