JAVA jdbc连接数据库

之前小伙伴叫我帮她写毕业设计,然后想起这道茬。多记录下曾经写的东西,总之,方便你我他

直接上代码,这里是用的MySql数据库,数据库增删改查主要类

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
 * 通用增删改查基类
 * @author 
 *
 */
public class BaseDao {
    
     private String user=MyProperties.getInstances().getProperty("user");
     private String password=MyProperties.getInstances().getProperty("password");
     private String url=MyProperties.getInstances().getProperty("url");
     private static String driver=MyProperties.getInstances().getProperty("driver");
     private Connection conn;
     private PreparedStatement ps;
     private ResultSet rs;
     private static BaseDao dao;
     private BaseDao(){};
     public static BaseDao getInstance(){
         if(dao==null){
             synchronized (BaseDao.class) {
                if(dao==null){
                    dao=new BaseDao();
                }
            }
         }
         return dao;
     }
     static{
         try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
     }
     public void getConnection(){
         try {
            conn=DriverManager.getConnection(url,user,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
     }
     
    /**
     * 更新数据库
     * @param sql sql语句
     * @param obj 传递的参数
     * @return
     */
     public int executeUpdate(String sql,Object[]obj,SearchBackCall back){
         int num=0;
         getConnection();
         try {
            ps=conn.prepareStatement(sql);
            if(obj!=null&&obj.length>0){
                for(int i=0;i<obj.length;i++)
                ps.setObject(i+1, obj[i]);
            }
            num=ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            if(back!=null){
            back.onFail();
            }
        }
         finally{
             release();
         }
         return num;
     } 
     /**
      * 查询
      * @param sql sql语句
      * @param obj 传入的参数
      * @param cls  返回的类
      * @return
      */
      public List executeQuery(String sql,Object[]obj,Class cls ){
          List list = new ArrayList();
          getConnection();
          try {
            ps=conn.prepareStatement(sql);
            if(obj!=null&&obj.length>0){
                for(int i=0;i<obj.length;i++){
                    ps.setObject(i+1,obj[i]);
                }
            }
            rs=ps.executeQuery();
            Field[]fds=cls.getDeclaredFields();
            while(rs.next()){
                Object object=cls.newInstance();
                for(int i=0;i<fds.length;i++){
                    Field f=fds[i];
                    f.setAccessible(true);
                     String type = 
                              f.getType().getName();
                          if(type.equals("java.lang.String")){
                              f.set(object, rs.getString(i+1));
                          }else if(type.equals("int")){
                              f.set(object, rs.getInt(i+1));
                          }else if(type.equals("double")){
                              f.set(object, rs.getDouble(i+1));
                          }else if(type.equals("float")){
                              f.set(object, rs.getFloat(i+1));
                          }else if(type.equals("java.util.Date")){
                              f.set(object, rs.getDate(i+1));
                          }
                }
                list.add(object);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          finally{
              release();
          }
         return list; 
      }
    /**
     * 关闭流
     */
    private void release(){
        try{
            if(rs!=null)
                rs.close();
            if(ps!=null)
                ps.close();
            if(conn!=null)
                conn.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

然后是获取文件的类

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
 * 这是读取文件类
 */
public class MyProperties extends Properties{
private static MyProperties mProperties;
private MyProperties(){
    InputStream is=null;
    try {
        is=getClass().getResourceAsStream("/pro.properties");
        this.load(is);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}    
    public static MyProperties getInstances(){
    
    if(mProperties==null){
        synchronized (MyProperties.class) {
            if(mProperties==null){
                mProperties=new MyProperties();
            }
        }
    }
    return mProperties;
    
    }
 }

ok,有这两个就够了

然后举个例子,查询:

List<TransObj>list =BaseDao.getInstance().executeQuery(
                "select * from "+GlobalVariable.TRANS_TABLE, 
                null, 
                TransObj.class);

删除:

int i=BaseDao.getInstance().
        executeUpdate("delete from "+GlobalVariable.CARD_TABLE+" where account=?"
        ,new String[]{account}
        , null);

增加:

BaseDao.getInstance().executeUpdate("insert into "+GlobalVariable.USER_TABLE+"(idcard,account,mobile,name) values(?,?,?,?)"
                    ,new Object[]{idCard,account,mobile,name},null);

修改:

int i=BaseDao.getInstance().executeUpdate(
                "update "+GlobalVariable.CARD_TABLE+" set savetype=?,moneytype=?,isguashi=? where account=?",
                new Object[]{savetype,moneytype,isguashi,account},null);

ok

 

posted on 2016-10-28 17:42  程序小渣渣  阅读(373)  评论(0编辑  收藏  举报

导航