1. 程式人生 > >java連線資料庫()的多種方法

java連線資料庫()的多種方法

0.準備工作,有mysql,資料庫,表格

1,使用原生的jdbc來連線(需要lib/mysql-connector-java-5.0.4-bin.jar);javax.sql

	public static Connection getConnection() throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://localhost:3306/web08";
		return DriverManager.getConnection(url, "root", "root");
	}

---------------------------------------------------------
@Test
	public void query() {
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			con = getConnection();
			stmt = con.createStatement();
			String sql = "select * from user";
			rs = stmt.executeQuery(sql);
			while(rs.next()) {
				String username = rs.getString(1);//從1開始
				String password = rs.getString(2);//引數改為列名更好
				System.out.println(username + ", " + password);
			}
		} catch(Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if(rs != null) rs.close();
				if(stmt != null) stmt.close();
				if(con != null) con.close();
			} catch(SQLException e) {}
		}
	}
	//有被注入的風險
---------------------------------------------------------------------------------
//改進
String sql = “select * from tab_student where s_number=?”;
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, “S_1001”);
ResultSet rs = pstmt.executeQuery();
rs.close();
pstmt.clearParameters();
pstmt.setString(1, “S_1002”);
rs = pstmt.executeQuery();

2.自定義資料庫連線池,實現DateSource介面
2.1裝飾者設計模式,擴充套件
後期再去補充

3.使用第三方的C3P0
C3P0是一個開源的JDBC連線池,它實現了資料來源和JNDI繫結,支援JDBC3規範和JDBC2的標準擴充套件。目前使用它的開源專案有Hibernate,Spring等。
在專案的src目錄下建立c3p0-config.xml檔案,當然你也可以建立一個c3p0.properties檔案

public class JDBCUtils2 {
	private static final ComboPooledDataSource DATA_SOURCE =new ComboPooledDataSource();
	/**
	 * 獲得連線的方法
	 */
	public static Connection getConnection(){
		Connection conn = null;
		try {
			conn = DATA_SOURCE.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

4.使用第三方的DBCP
DBCP(DataBase connection pool),資料庫連線池。是 apache 上的一個 java 連線池專案,也是 tomcat 使用的連線池元件。
單獨使用dbcp需要2個包:commons-dbcp.jar,commons-pool.jar由於建立資料庫連線是一個非常耗時耗資源的行為,所以通過連線池預先同資料庫建立一些連線,放在記憶體中,應用程式需要建立資料庫連線時直接到連線池中申請一個就行,用完後再放回去。

/**
	 * 手動方式:
	 */
	public void demo1(){
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql:///web_07");
		dataSource.setUsername("root");
		dataSource.setPassword("123");
		try{
			// 獲得連線:
			conn = dataSource.getConnection();
			// 編寫SQL:
			String sql = "select * from category";
			// 預編譯SQL:
			stmt = conn.prepareStatement(sql);
			// 執行SQL:
			rs = stmt.executeQuery();
			while(rs.next()){
				System.out.println(rs.getInt("cid")+"   "+rs.getString("cname"));
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JDBCUtils.release(rs,stmt, conn);
		}
	}
	
	@Test
	/**
	 * 配置檔案方式:
	 */
	public void demo2(){
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		Properties properties = new Properties();
		
		try{
			properties.load(new FileInputStream("src/dbcpconfig.properties"));
			DataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
			// 獲得連線:
			conn = dataSource.getConnection();
			// 編寫SQL:
			String sql = "select * from category";
			// 預編譯SQL:
			stmt = conn.prepareStatement(sql);
			// 執行SQL:
			rs = stmt.executeQuery();
			while(rs.next()){
				System.out.println(rs.getInt("cid")+"   "+rs.getString("cname"));
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JDBCUtils.release(rs,stmt, conn);
		}
	}



5.使用第三方的Druid
dbconfig.properties配置檔案

public class DruidUtil {
// 得到一個Druid的資料來源
private static DruidDataSource dataSource = null;

static{
    Properties properties = new Properties();
    try {
        //載入配置檔案
        //properties.load(new FileInputStream("build/classes/dbconfig.properties"));
        //下面這種寫法會從classpath下來查詢配置檔案
        properties.load(DruidUtil.class.getClassLoader().getResourceAsStream("dbconfig.properties"));
        //得到一個數據源 
        dataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
    } catch (Exception e) {
        e.printStackTrace();
    }
}


// 從資料來源中得到一個連線物件
// 這個返回的connection實際上是Druid經過裝飾之後的connection
public static Connection getConnection() {
    try {
        return dataSource.getConnection();
    } catch (SQLException e) {
        throw new RuntimeException("伺服器錯誤");
    }
}

}
package com.monkey1024.jdbc.test;

import java.sql.Connection;
import java.sql.PreparedStatement;

import com.monkey1024.jdbc.util.DruidUtil;

public class DruidTest {

public static void main(String[] args) {
    insert();
    try {
        //睡眠一下方便檢視狀態
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public static void insert() {

    String sql = "insert into t_user(id,name) values('12012','jack')";
    try (Connection conn = DruidUtil.getConnection(); 
            PreparedStatement ps = conn.prepareStatement(sql)) {
        ps.executeUpdate();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

}


6.返回結果處理
6.1ResultSetHandler
DBUtils提供了一個介面ResultSetHandler,它就是用來ResultSet轉換成目標型別的工具。你可以自己去實現這個介面,把ResultSet轉換成你想要的型別。
DBUtils提供了很多個ResultSetHandler介面的實現,這些實現已經基本夠用了,我們通常不用自己去實現ResultSet介面了。
6.1.1	MapHandler:單行處理器!把結果集轉換成Map<String,Object>,其中列名為鍵!
6.1.2	MapListHandler:多行處理器!把結果集轉換成List<Map<String,Object>>;
6.1.3	BeanHandler:單行處理器!把結果集轉換成Bean,該處理器需要Class引數,即Bean的型別;
6.1.4	BeanListHandler:多行處理器!把結果集轉換成List<Bean>;
6.2QueryRunner
public <T> T query(String sql, ResultSetHandler<T> rh, Object… params)

@Test
public void fun1() throws SQLException {
	DataSource ds = JdbcUtils.getDataSource();
	QueryRunner qr = new QueryRunner(ds);
	String sql = "select * from tab_student where number=?";
	Map<String,Object> map = qr.query(sql, new MapHandler(), "S_2000");
	System.out.println(map);
}

@Test
public void fun2() throws SQLException {
	DataSource ds = JdbcUtils.getDataSource();
	QueryRunner qr = new QueryRunner(ds);
	String sql = "select * from tab_student";
	List<Map<String,Object>> list = qr.query(sql, new MapListHandler());
	for(Map<String,Object> map : list) {
		System.out.println(map);
	}
}

@Test
public void fun3() throws SQLException {
	DataSource ds = JdbcUtils.getDataSource();
	QueryRunner qr = new QueryRunner(ds);
	String sql = "select * from tab_student where number=?";
	Student stu = qr.query(sql, new BeanHandler<Student>(Student.class), "S_2000");
	System.out.println(stu);
}

@Test
public void fun4() throws SQLException {
	DataSource ds = JdbcUtils.getDataSource();
	QueryRunner qr = new QueryRunner(ds);
	String sql = "select * from tab_student";
	List<Student> list = qr.query(sql, new BeanListHandler<Student>(Student.class));
	for(Student stu : list) {
		System.out.println(stu);
	}
}

@Test
public void fun5() throws SQLException {
	DataSource ds = JdbcUtils.getDataSource();
	QueryRunner qr = new QueryRunner(ds);
	String sql = "select * from tab_student";
	List<Object> list = qr.query(sql, new ColumnListHandler("name"));
	for(Object s : list) {
		System.out.println(s);
	}
}

@Test