1. 程式人生 > >JDBC例子和c3p0連線池

JDBC例子和c3p0連線池

 

package com.tedu;

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

/**
 * JDBC快速入門案例
 * 
 * @author Administrator
 *
 */
public class JDBCDemo1 {

	public static void main(String[] args) {
		Connection conn = null;
		Statement stat = null;
		ResultSet rs = null;
		try {
			// 1.註冊資料庫驅動(讓JDBC程式管理mysql的jar包)
			Class.forName("com.mysql.jdbc.Driver");
			// 2.獲取資料庫連線()
			// Connection conn =
			// DriverManager.getConnection("jdbc:mysql://localhost:3306/jt_db","root","");
			conn = DriverManager.getConnection("jdbc:mysql:///jt_db?useUnicode=true&characterEncoding=utf-8", "root", "");
			// 3.獲取傳輸器
			stat = conn.createStatement();
			// 4.宣告SQL併發送SQL到資料庫執行,返回執行結果
			String sql = "select * from account";
			rs = stat.executeQuery(sql);
			// 5.處理結果
			System.out.println(rs.next());
			while (rs.next()) {
				int id = rs.getInt("id");
				String name = rs.getString("name");
				double money = rs.getDouble("money");
				System.out.println(id + ":" + name + ":" + money);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("查詢失敗");
		} finally {
			// 6.釋放資源(越晚獲取的越先關閉)
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					rs = null;
				}
			}
			if (stat != null) {
				try {
					stat.close();
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					stat = null;
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					conn = null;
				}
			}
		}
	}
}

查詢用的是executeQuery(sql)    增刪改用的是executeUpdate(sql)

 

使用c3p0連線池,匯入c3p0的jar包,要注意c3p0-config.xml檔案的配置  ,如下:

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <default-config>
        <property name="driverClass">
            com.mysql.jdbc.Driver
        </property>
        <property name="jdbcUrl">
            jdbc:mysql:///jt_db?useUnicode=true&amp;characterEncoding=utf-8
        </property>
        <property name="user">
            root
        </property>
        <property name="password">
            
        </property>
    </default-config>
</c3p0-config>

 

package com.tedu;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * JDBC快速入門案例
 * 
 * @author Administrator
 *
 */
public class Testc3p0 {

	@SuppressWarnings({ "unused", "null" })
	public static void main(String[] args) {
		Connection conn = null;
		Statement stat = null;
		ResultSet rs = null;
		//0.建立一個連線池物件
		ComboPooledDataSource pool =new ComboPooledDataSource();
		try {
//			//配置連線資料庫的基本資訊
//			pool.setDriverClass("com.mysql.jdbc.Driver");
//			pool.setJdbcUrl("jdbc:mysql:///jt_db?useUnicode=true&characterEncoding=utf8");
//			pool.setUser("root");
//			pool.setPassword("");
			//1.從連線池中獲取一個連線物件
			 conn = pool.getConnection();
			// 3.獲取傳輸器
			stat = conn.createStatement();
			// 4.宣告SQL併發送SQL到資料庫執行,返回執行結果
			String sql = "select * from account";
			rs = stat.executeQuery(sql);
			// 5.處理結果
			while (rs.next()) {
				int id = rs.getInt("id");
				String name = rs.getString("name");
				double money = rs.getDouble("money");
				System.out.println(id + ":" + name + ":" + money);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("查詢失敗");
		} finally {
			// 6.釋放資源(越晚獲取的越先關閉)
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					rs = null;
				}
			}
			if (stat != null) {
				try {
					stat.close();
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					stat = null;
				}
			}
			if (conn != null) {
				try {
					//如果conn是自己建立的,就是原生的Connection,沒有被改造,呼叫close就是關閉連線,
					//如果conn是從連線池中獲取的連線物件,這個連線已經被改造過了,呼叫close方法就是將連線還給連線池
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					conn = null;
				}
			}
		}
	}
}

PreparedStatement 可以有效的防止SQL注入,例子:

public static Connection getConn() throws Exception{
		//1.註冊驅動
		Class.forName( "com.mysql.jdbc.Driver" );
		//2.獲取連線
		Connection conn = DriverManager.getConnection(
				"jdbc:mysql:///jt_db?useUnicode=true&characterEncoding=utf-8", 
				"root", 
				"");
		return conn;
	}
public static void close(Connection conn, 
			Statement stat, ResultSet rs){
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally{
				rs = null;
			}
		}
		if(stat != null){
			try {
				stat.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally{
				stat = null;
			}
		}
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally{
				conn = null;
			}
		}
	}
private static void loginByPS(String username, String pwd) {
		Connection conn =null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			conn=JDBCUtil.getConn();
			String sql="select * from user where username=? and password=?";
			ps=conn.prepareStatement(sql);
			ps.setString(1, username);
			ps.setString(2, pwd);
			rs=ps.executeQuery();
			if(rs.next())
			{
				System.out.println("登入成功!!!");
			}else{
				System.out.println("使用者名稱或密碼不正確");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("登入失敗!!!");
		}finally{
			//釋放資源
			JDBCUtil.close(conn, ps, rs);
		}
	}