package com.jdbc;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.PreparedStatement;
public class Jdbc {
//C:/Users/asus/Desktop/qq.txt
private static final ComboPooledDataSource ds=new ComboPooledDataSource();
static {
ds.setJdbcUrl("jdbc:mysql://localhost:3306/ll");
ds.setUser("root");
ds.setPassword("soul0123");
try {
ds.setDriverClass("com.mysql.jdbc.Driver");
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection(){
try {
return ds.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void release(ResultSet rs,PreparedStatement ps,Connection con){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class BaseDao {
public static void Base(String sql,Object...args){
//获取链接
Connection con = Jdbc.getConnection();
try {
//获取preparedsatement
PreparedStatement ps = con.prepareStatement(sql);
//填充占位符
for (int i = 0; i < args.length; i++) {
Object obj=args[i];
ps.setObject(i+1, args[i]);
}
//执行sql
ps.executeUpdate();
//关闭数据
Jdbc.release(null, ps, con);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void Insert() {
// 1.获取连接
/*
* 2.获取preparestatment
*
* 3.填充占位符 4.执行sql 5.关闭
*
*/
String sql = ("insert into qwer values(null,?)");
BaseDao.Base(sql, "gg");
}
@Test
public void delete() {
String sql = "delete from qwer where id=?";
BaseDao.Base(sql, 2);
}
@Test
public void update() {
String sql = "update qwer set name=? where id=?";
BaseDao.Base(sql, "JS", 22);
}