//DBUtils
package com.mhys.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtils
{
static{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConn(){
Connection conn =null ;
try
{
conn= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/business", "root", "123456");
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static void closeAll(ResultSet rs , PreparedStatement ps , Connection conn){
try{
if(null!=rs){ rs.close();}
if(null!=ps){ps.close();}
if(null!=conn){conn.close();}
}catch(Exception e ){}
}
public static void main(String[] args)
{
System.out.println(getConn());
}
}
//BaseDao
package com.mhys.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import com.mhys.utils.DBUtils;
public class BaseDao
{
Connection conn =null;
PreparedStatement ps =null;
ResultSet rs =null;
/**
* 开启事务,并返回自增Id的查询方法
* @param sql 要执行的sql语句
*@param objs 需要取代? 的数组
*@param conn 事务执行需要共用的 conn*/
public int save_getKey(String sql, Object[] objs ,Connection conn) throws SQLException{
int id =0;
//查询窗口, 用来进行sql语句 的执行,第二个参数代表, 需要返回自增的id主键
ps =conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
// 用具体的数值取 取代?
if(objs!=null){
for(int i =0;i<objs.length;i++){
ps.setObject(i+1, objs[i]);
}}
ps.executeUpdate();
rs =ps.getGeneratedKeys();
if(rs.next()){
id=rs.getInt(1);
}
return id;
}
public void save_upt_del(String sql, Object[] objs ){
try
{
//获取数据库连接
conn = DBUtils.getConn();
//查询窗口, 用来进行sql语句 的编辑
ps =conn.prepareStatement(sql);
// 用具体的数值取 取代?
if(objs!=null){
for(int i =0;i<objs.length;i++){
ps.setObject(i+1, objs[i]);
}}
//执行sql
ps.executeUpdate();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtils.closeAll(null, ps, conn);
}
}
public ResultSet queryByArray(String sql , Object[] objs){
try{
conn = DBUtils.getConn();
ps = conn.prepareStatement(sql);
if(objs!=null){
for(int i =0;i<objs.length;i++){
ps.setObject(i+1, objs[i]);
}}
rs = ps.executeQuery();
}catch(Exception e){}
return rs;
}
public void save_upt_del(String sql, List<Object> objs ){
try
{
conn = DBUtils.getConn();
ps =conn.prepareStatement(sql);
if(objs!=null){
for(int i =0;i<objs.size();i++){
ps.setObject(i+1, objs.get(i));
}}
ps.executeUpdate();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtils.closeAll(null, ps, conn);
}
}
public ResultSet query(String sql , List<Object> list){
try{
conn = DBUtils.getConn();
ps = conn.prepareStatement(sql);
if(list!=null){
for(int i =0;i<list.size();i++){
ps.setObject(i+1, list.get(i));
}}
rs = ps.executeQuery();
}catch(Exception e){}
return rs;
}
}