其中的getConnetction方法和excute方法,分别是获取数据库的连接,以及对信息的查询,为了防止sql注入的问题出现,我在此使用的是preparestatement。
package com.su.dao;
import javax.xml.transform.Result;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class BaseDao {
private static String driver;
private static String url;
private static String username;
private static String password;
//要用静态代码块,这样加载类的时候就会完成初始化
static {
Properties properties=new Properties();
InputStream is=BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
driver=properties.getProperty("driver");
url=properties.getProperty("url");
username=properties.getProperty("username");
password=properties.getProperty("driver");
}
//获取数据库的连接
public static Connection getConnection(){
Connection connection=null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return connection;
}
//编写查询工具类
public static ResultSet execute(Connection connection,String sql,Object[] param,ResultSet rs) throws SQLException {
PreparedStatement ps=connection.prepareStatement(sql);
for (int i = 0; i < param.length; i++) {
//setObject,占位符从1开始,但是我们的数组是从0开始
ps.setObject(i+1,param[i]);
}
int updateRows=ps.executeUpdate();
return rs;
}
}