创建配置文件
在src 目录下 (右击),创建文件 (new file) ,文件名为 xxx.properties,在文件内存放数据库配置信息
如下所创建的文件 db.properties(说明:连接数据库为 pet , 用户名为 root ,密码为123456):
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/pet?useUnicode=true&characterEncoding=utf-8 username=root password=123456
定义工具类
public class BaseUtil {
/**
数据库配置信息从配置文件中获取
连接数据库操作
*/
public static Connection linked() {
//加载数据库信息配置
Properties pro=new Properties();
//getClassLoader()加载 getResourceAsStream()获取 配置文件到输入流
InputStream is= BaseUtil.class.getClassLoader().getResourceAsStream("db.properties");
Connection conn=null;
try {
//load()方法 从输入流中读取属性列表(信息)
pro.load(is);
//getProperty()方法 读取相应的数据库配置信息
//加载驱动
Class.forName(pro.getProperty("driver"));
//建立数据库连接
conn= DriverManager.getConnection(pro.getProperty("url"),pro.getProperty("username"),pro.getProperty("password"));
}catch (Exception e){
e.printStackTrace();
}
return conn;
}
/**
*关闭数据库操作
*/
public static void close(ResultSet rs, PreparedStatement stem, Connection conn){
try {
if(null!=rs)rs.close();
}catch (Exception e){
e.printStackTrace();
}
try {
if(null!=stem)stem.close();
}catch (Exception e){
e.printStackTrace();
}
try {
if(null!=conn)conn.close();
}catch ( Exception e){
e.printStackTrace();
}
}
/**
* 增、删、改的操作
* Object...param 表示在调用 exceuteUpdate()方法操作数据时,此数组参数可填可不填,是任意的
当然也可用 Object [] param 参数
*/
public int exceuteUpdate(String sql,Object...param){
Connection conn=BaseUtil.linked();
PreparedStatement pre=null;
int num=0;
try {
pre = conn.prepareStatement(sql);
if (null != param){
for (int i=0;i<param.length;i++){
//为预编译sql设置参数
pre.setObject(i+1,param[i]);
}
}
num=pre.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}finally {
BaseUtil.close(null,pre,conn);
}
return num;
}
}
}
使用工具类的 exceuteUpdate( )方法,进行数据的增、删、改操作示例
如下 是对数据进行修改的操作:/** * PetDao针对MYSQL数据库的实现类 * 继承 BaseUtil工具类,以便调用 exceuteUpdate()方法进行增删改操作 */ public class PetDaoImpl extends BaseUtil implements PetDao { public int update(Pet pet) { /** * 方式一: executeUpdate(String sql,Object [] param) 第二个参数为Object [] param */ String sql="update pets set status=0 where pet_id=?"; Object [] param={pet.getPet_id()}; int rs=[this.]exceuteUpdate(sql,param); 或 int rs=[this.]exceuteUpdate(sql,new Object[]{pet.getPetId}) return rs; /** *方式二: executeUpdate(String sql,Object...param) 当第二个参数为Object...param时,不需再new Object对象来获得值 */ String sql="update pets set status=0 where pet_id=?"; int rs=[this.]executeUpdate(sql,pet.getPet_id()); return rs; }