create database mydb character set utf8;
alert database mydb character set utf8;
1.自定義連接池為了不去經(jīng)常創(chuàng)建連接和釋放對(duì)象而占用大量資源
-----JdbcTool3 -----------獲得connection(通過·)和釋放資源------------
public class JdbcTool3 {
private static String drive;
private static String sql;
private static String username;
private static String passord;
static {
try {
ClassLoader classLoader = JdbcTool3.class.getClassLoader();
InputStream input = classLoader.getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(input);
drive = properties.getProperty("driver");
sql = properties.getProperty("url");
username = properties.getProperty("username");
passord = properties.getProperty("psaaword");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection connection() {
try {
Class.forName(drive);
} catch (Exception e) {
e.printStackTrace();
}
Connection con = null;
try {
con = DriverManager.getConnection(sql, username, passord);
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void relese(Statement sta, Connection con, ResultSet res) {
if (res != null) {
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (sta != null) {
try {
sta.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
---------有了conn之后便是創(chuàng)建幾個(gè)放入連接池,在使用完后同樣回收到連接池---
implements 是重寫接口所以需要全部覆蓋
public class MyDatasource implements DataSource{
private static LinkedList<Connection> pool=new LinkedList<>();
static{
Connection conn=null;
for (int i = 0; i < 5; i++) {
conn=JdbcTool3.connection();
pool.add(conn);
}
}
/**放回池中
* @param conn
*/
public static void backConnection(Connection conn) {
pool.add(conn);
}
@Override
public Connection getConnection() throws SQLException {
if (pool.size()==0) {
Connection conn=null;
for (int i = 0; i < 5; i++) {
conn=JdbcTool3.connection();
pool.add(conn);
}
}
return pool.remove(0);
}
- 修飾者設(shè)計(jì)模式:為了將.close修改成把鏈接放回連接池而不是釋放
--------修改原本的功能重寫一個(gè)類繼承connection,為了修改.close方法--------
因?yàn)閷?shí)例化所以同樣需要重寫prepareStatement方法
public class ColectionMackClose implements Connection {
private static LinkedList<Connection> pool;
private static Connection con;
public ColectionMackClose(Connection con, LinkedList<Connection> pool) {
this.pool = pool;
this.con = con;
}
@Override
public void close() throws SQLException {
pool.add(con);
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return con.prepareStatement(sql);
}
----------獲得con之后用新的類ColectionMackClose 包裝得到重寫的con---------
public class MyDatasource1 implements DataSource{
private static LinkedList<Connection> pool=new LinkedList<>();
static{
Connection conn=null;
for (int i = 0; i < 5; i++) {
conn=JdbcTool3.connection();
ColectionMackClose myCollection = new ColectionMackClose(conn, pool);
pool.add(myCollection);
}
}
@Override
public Connection getConnection() throws SQLException {
if (pool.size()==0) {
Connection conn=null;
for (int i = 0; i < 5; i++) {
conn=JdbcTool3.connection();
ColectionMackClose myCollection = new ColectionMackClose(conn, pool);
pool.add(myCollection);
}
}
return pool.remove(0);
}
2.c3p0連接池,使用較多
- 導(dǎo)包
從SourceForge 網(wǎng)站下載最新的版本
http://sourceforge.net/projects/c3p0/
出現(xiàn)找不到或無法加載主類 cn.fb.textDatasource.C3p0Text,從項(xiàng)目文件夾.path文件中刪除多余路徑
注意添加兩個(gè)文件c3p0-0.9.5.2.jar和mchange-commons-java-0.2.11.jar(有時(shí)候沒mchange也行,和版本有關(guān)?)

圖片.png
------c3p0-config.xml名稱唯一放在scr下-----
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///web09</property>
<property name="user">root</property>
<property name="password">0616</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
<named-config name="text">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///web09</property>
<property name="user">root</property>
<property name="password">0616</property>
</named-config>
</c3p0-config>
------c3p0會(huì)自動(dòng)獲取xml文件配置---使用set方法設(shè)置也行---
public class C3p0Utiles {
private static ComboPooledDataSource datasourse=new ComboPooledDataSource("text");如果沒參數(shù)會(huì)自動(dòng)加載default
public static ComboPooledDataSource getCombpdatasource() {
return datasourse;
}
public static Connection getCon() {
try {
return datasourse.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
-----------text----------------
public void textadd2() {
Connection con = null;
PreparedStatement pst = null;
try {
con =C3p0Utiles.getCon();
String sql = "insert into product values(?,?,?,null)";
pst = con.prepareStatement(sql);
pst.setString(1, "p022");
pst.setString(2, "云河2");
pst.setDouble(3, 30);
int row = pst.executeUpdate();
if (row > 0) {
System.out.println("添加成功");
} else {
System.out.println("添加失敗");
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}finally {
JdbcTool3.relese(pst, con, null);
}
}
3.dbcp

圖片.png
同樣使用.properties文件,BasicDataSourceFactory創(chuàng)建
private static DataSource dataSource;
static {
try {
InputStream input = DbcpUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties pro = new Properties();
pro.load(input);
dataSource = BasicDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static DataSource getdatasource() {
return dataSource;
}
public static Connection getconnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
-------------properties----放在src下-----------
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/web09?useUnicode=true&characterEncoding=utf8
username=root
psaaword=0616
4.dbutils

圖片.png
?MapHandler:單行處理器!把結(jié)果集轉(zhuǎn)換成Map<String,Object>,其中列名為鍵!
?MapListHandler:多行處理器!把結(jié)果集轉(zhuǎn)換成List<Map<String,Object>>;
?BeanHandler:單行處理器!把結(jié)果集轉(zhuǎn)換成Bean,該處理器需要Class參數(shù),即Bean的類型;
?BeanListHandler:多行處理器!把結(jié)果集轉(zhuǎn)換成List<Bean>;
?ColumnListHandler:多行單列處理器!把結(jié)果集轉(zhuǎn)換成List<Object>,使用ColumnListHandler時(shí)需要指定某一列的名稱或編號(hào),例如:new ColumListHandler(“name”)表示把name列的數(shù)據(jù)放到List中。
?ScalarHandler:單行單列處理器!把結(jié)果集轉(zhuǎn)換成Object。一般用于聚集查詢,例如select count(*) from tab_student。
--------------------------------------------
@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()[把一行記錄轉(zhuǎn)換成一個(gè)Map,其中鍵為列名稱,值為列值], "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()[把轉(zhuǎn)換集轉(zhuǎn)換成List<Map>,其中每個(gè)Map對(duì)應(yīng)一行記錄]);
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)[把結(jié)果集轉(zhuǎn)換成一個(gè)Bean對(duì)象,在使用BeanHandler時(shí)需要指定Class,即Bean的類型], "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));[需要將列名化為屬性把結(jié)果集轉(zhuǎn)換成List<Bean>,其中每個(gè)Bean對(duì)應(yīng)一行記錄]
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")[多行單例處理器,即獲取name列數(shù)據(jù)]);
for(Object s : list) {
System.out.println(s);
}
}
@Test
public void fun6() throws SQLException {
DataSource ds = JdbcUtils.getDataSource();
QueryRunner qr = new QueryRunner(ds);
String sql = "select count(*) from tab_student";
Number number = (Number)qr.query(sql, new ScalarHandler()[單行單列處理器,一般用于聚合查詢,在使用ScalarHandler時(shí)可以指定列名,如果不指定,默認(rèn)為第1列。]);
int cnt = number.intValue();[對(duì)聚合函數(shù)的查詢結(jié)果,有的驅(qū)動(dòng)返回的是Long,有的返回的是BigInteger,所以這里我把它轉(zhuǎn)換成Number,Number是Long和BigInteger的父類!然后我再調(diào)用Number的intValue()或longValue()方法就OK了。]
System.out.println(cnt);
}
@Test
public void add() {
try {
QueryRunner qr = new QueryRunner(C3p0Utiles.getCombpdatasource());
String sql = "insert into product values(?,?,?,null);";
Object[] product = { "p017", "抱抱", 2000 };
int row = qr.update(sql, product);
if (row > 0) {
System.out.println("添加成功");
} else {
System.out.println("添加失敗");
}
} catch (SQLException e) {
e.printStackTrace();
}