Java tool class for linking Oracle database

How java connects to Oracle database

1 Features: oracle.jdbc.OracleDriver is a registered oracle driver class;

jdbc:oracle:thin:@localhost:1521:xe: the way to connect to oracle: network protocol + access mode + IP + port number + xe database;

user: hr database username

Password: User password for the hr database

Disadvantages: The statement method to connect to the database is easy to be injected by hackers, all insecure. Now this method is rarely used in enterprises.

After connecting to the database, the connection must be closed. This is the easiest to forget to call the close() method to close the connection.

public static void main(String[] args) throws Exception {

// 1 register the driver class

Class.forName("oracle.jdbc.OracleDriver");

 

// 2 create the connection

String url="jdbc:oracle:thin:@localhost:1521:xe";

Connection con = DriverManager.getConnection(url,"hr","hr");

 

// 3 create stm

Statement stm = con.createStatement();

 

// 4 execute SQL

String sql = "select accountNo cardid,accountName name,balance bal from accounts";

// executeQuery: Execute DQL statement (select), return ResultSet type, representing the queried virtual table

ResultSet rs = stm.executeQuery(sql);

 

// 5 Process the query result

while (rs.next()){

// Get the value of each field rs.getXxx("field name") rs.getXxx(index)

int no = rs.getInt("cardid");

double bal = rs.getDouble("bal");

String name = rs.getString(2);  

String pwd = rs.getString("password");

 

System.out.println("卡号:" + no +" , name=" + name +", bal=" + bal+", pwd=" + pwd);

}

 

// 6 release resources

if (rs != null)

rs.close();

if (stm != null)

stm.close();

if (con != null)

con.close();

}

 

2 Features: io reads the information in the accessory file db.properties and writes it for yourself in the configuration file is the mydriver path myurl The way to connect to oracle: network protocol + access method + IP + port number + xe database myuser database user name mypasswoed: database access password

Encapsulating the above information into the configuration file can be reused to reduce the redundancy of the code, use one call at a time

Close the connection encapsulation with the getRelease() method and then call the dao layer when it needs to be used. Generally, the connection is not closed. Generally, the connection is closed at the service layer, otherwise it is easy to cause business errors.

private static Properties prop = new Properties();

Advantages: encapsulated into methods to be called when needed to reduce code redundancy 

Improved safety performance: ? Placeholder assignment is safer than the first method to solve problems such as injection attacks

 

Disadvantages: It belongs to the singleton mode and multi-threaded concurrent access is prone to thread safety problems. For example, during the Double Eleven spike, multiple users access the same resource critical resource objects at the same time. If locking, it will cause threads to wait without locking. A large number of users concurrent access will cause thread safety problems.

// When the class is loaded, read the configuration file once

static{

try {

// Get the input stream of the configuration file

InputStream is = JdbcUtil2.class.getResourceAsStream("/com/baizhi/day2/db.properties");

 

// Use the load method of prop to automatically read the file

prop.load(is);

} catch (IOException e) {

e.printStackTrace ();

} finally {

// close the stream

}

}

 

// get the connection

public static Connection getConn(){

Connection con = null;

try {

// Get the content of the configuration file

String driverClassName = prop.getProperty("mydriverclass");

String url = prop.getProperty("myurl");

String userName = prop.getProperty("username");

String pwd = prop.getProperty("password");

 

Class.forName (driverClassName);

con = DriverManager.getConnection(url, userName, pwd);

} catch (Exception e) {

e.printStackTrace ();

throw new RuntimeException(e);

}

return con;

}

 

// release resources

public static void release(ResultSet rs, Statement stm, Connection con){

if (rs != null){

try {

rs.close();

} catch (Exception e) {

e.printStackTrace ();

throw new RuntimeException(e);

}

}

if (stm != null){

try {

stm.close();

} catch (Exception e) {

e.printStackTrace ();

throw new RuntimeException(e);

}

}

if (con != null){

try {

con.close();

} catch (Exception e) {

e.printStackTrace ();

throw new RuntimeException(e);

}

}

}

 

3 Features/Benefits: The introduction of the thread object ThreadLocal can support simultaneous access by a large number of users for multi-user concurrent access problems

public class JdbcUtil {

private static Properties prop = new Properties();

 

// read configuration file

static {

try {

InputStream is = JdbcUtil.class.getResourceAsStream("/com/baizhi/day3/db.properties");

prop.load(is);

} catch (IOException e) {

e.printStackTrace ();

throw new RuntimeException(e);

} finally {

}

}

 

// add static member variable

private static final ThreadLocal<Connection> thl = new ThreadLocal<Connection>();

 

// get the connection

public static Connection getConn() {

Connection conn = thl.get(); // get value from thread local variable

try {

if (conn == null) { // no value

// Get the contents of the configuration file

String driverClass = prop.getProperty("mydriverclass");

String myurl = prop.getProperty("myurl");

String username = prop.getProperty("username");

String password = prop.getProperty("password");

 

Class.forName(driverClass);

conn = DriverManager.getConnection(myurl, username, password);

 

thl.set(conn); // save conn to thl

}

} catch (Exception e) {

e.printStackTrace ();

throw new RuntimeException(e);

}

return conn;

}

 

// release resources

public static void release(ResultSet rs, Statement stm, Connection conn) {

try {

if (rs != null)

rs.close();

if (stm != null)

stm.close();

if (conn != null){

conn.close();  

thl.remove(); // closed connections must be removed from thl ************

}

} catch (Exception e) {

e.printStackTrace ();

throw new RuntimeException(e);

}

}

}

4: Features/Benefits: Introducing a data pool to reduce the number of database accesses and improve execution efficiency 

 

public class JdbcUtilPool {

public static final ThreadLocal thl=new ThreadLocal();

public static Connection getConn(){

Connection conn=(Connection) thl.get();

try {

if(conn == null){

//Get the root where the resource is located

Context ctx = new InitialContext();

// Get resources by name and directory

javax.sql.DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/myoracle");

//Get the connection from the connection pool

conn=ds.getConnection();

}

} catch (Exception e) {

e.printStackTrace ();

throw new RuntimeException();

}

return conn;

}

public static void release(ResultSet rs,PreparedStatement pstm,Connection conn){

try {

if (rs!=null) rs.close(); 

} catch (Exception e) {

e.printStackTrace ();

throw new RuntimeException();

}

try {

if (pstm!=null) pstm.close(); 

} catch (Exception e) {

e.printStackTrace ();

throw new RuntimeException();

}

try {

if (conn!=null) {

conn.close(); //Return the connection to the connection pool

thl .remove();//Clear the thread connection

}

} catch (Exception e) {

e.printStackTrace ();

throw new RuntimeException();

}

}

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324852442&siteId=291194637