连接oracle数据库

我们在后台经常需要连接数据,操作数据库,我这里给出一个实例(其实我也是看别人的博客的,感谢原博主)
package com.Util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DbUtil {
	private Connection con;
	private String user = "scott";//数据库用户名,
	private String password = "orcl123";//密码
	private String className = "oracle.jdbc.driver.OracleDriver";
	private String url = "jdbc:oracle:thin:@localhost:1521:ORCL";// 我是用本地Tomcat,所以写localhost

	public static void main(String[] args) {//想要测试可以直接执行此代码,
		// TODO Auto-generated method stub
		DbUtil c = new DbUtil();
		//c.ConnectOracle();
		Connection con2 = c.getCon();
		c.closed(con2);

	}

	public void ConnectOracle() {
		try {
			Class.forName(className);
			System.out.println("加载数据库驱动成功!");
		} catch (ClassNotFoundException e) {
			System.out.println("加载数据库驱动失败!");
			e.printStackTrace();
		}
	}

	/** 创建数据库连接 */
	public Connection getCon() {
		try {
			Class.forName(className);
			//System.out.println("加载数据库驱动成功!");
		} catch (ClassNotFoundException e) {
			System.out.println("加载数据库驱动失败!");
			e.printStackTrace();
		}
		try {
			con =  DriverManager.getConnection(url, user, password);
			//System.out.println("创建数据库连接成功!");
		} catch (SQLException e) {
			System.out.print(con);
			System.out.println("创建数据库连接失败!");
			con = null;
			e.printStackTrace();
		}
		return con;
	}

	public void closed(Connection con)  {
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				System.out.println("数据库关闭失败");
				e.printStackTrace();
			}finally{
				//System.out.println("数据库关闭成功");
			}
		}
	}
}

你可能感兴趣的:(oracle)