[英]java - creating an oracle database connection
Does anyone know what the best way is to create a new oracle database connection. 有谁知道最好的方法是创建一个新的oracle数据库连接。 This is what I currently have:
这是我目前拥有的:
private static getConnection() throws Exception {
if (!isDriverRegistered){
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
isDriverRegistered = true;
}
return DrvierManager.getConnection(connectionString);
}
You are not supposed to register the driver yourself; 您不应该自己注册驾驶员。 the JDBC driver itself will do that, when its class is loaded.
JDBC驱动程序本身将在加载其类时执行此操作。 So, do not call
DriverManager.registerDriver
yourself. 因此,请勿自己调用
DriverManager.registerDriver
。
There are two steps: make sure the JDBC driver class is loaded, and get a connection. 分两个步骤:确保JDBC驱动程序类已加载,并获得连接。
To load the JDBC driver class, use a line like this: 要加载JDBC驱动程序类,请使用如下代码:
Class.forName("oracle.jdbc.OracleDriver");
Then get the connection with a call to DriverManager.getConnection
: 然后通过调用
DriverManager.getConnection
获得连接:
Connection conn = DriverManager.getConnection(connectionString);
Note that if you are using a newer JDBC version and a suitable driver, you do not even need to load the driver class explicitly; 请注意,如果您使用的是较新的JDBC版本和合适的驱动程序,则甚至无需显式加载驱动程序类。 it will be found and loaded automatically (via Java's service discovery mechanism).
它会被发现并自动加载(通过Java的服务发现机制)。 In that case you only need to call
DriverManager.getConnection
. 在这种情况下,您只需要调用
DriverManager.getConnection
。
this class may help you 这节课可能对你有帮助
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCHelper {
public static void close(Statement obj)
{
try
{
if(obj!=null)
obj.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet obj)
{
try
{
if(obj!=null)
obj.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public static void close(Connection obj)
{
try
{
if(obj!=null)
obj.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public static Connection getConnection()
{
Connection con = null;
String url = "url" //give url
String pwd = "password";//give password
String uid = "userId";//give userid
try
{
Class.forName("oracle.jdbc.OracleDriver"); //pass driver name
con = DriverManager.getConnection(url,uid,pwd);
con.setAutoCommit(false);
}
catch(Exception e)
{
if(con!=null)
try {
con.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
return con;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.