之前小伙伴叫我帮她写毕业设计,然后想起这道茬。多记录下曾经写的东西,总之,方便你我他
直接上代码,这里是用的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;i0){ for(int i=0;i
然后是获取文件的类
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,有这两个就够了
然后举个例子,查询:
Listlist =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