#以key=value 形式存储 ?useUnicode=true&characterEncoding=utf-8 解决中文乱码问题
//连接数据库
jdbc_url=jdbc:mysql://localhost:3306/telecom
//加载驱动
jdbc_driverClass=com.mysql.jdbc.Driver
//mysql的用户名
jdbc_username=root
//密码
jdbc_password=123
二、写一个工具类实现代码的复用
public class JDBCUtil {
//把文件加载到输入流中 读取属性文件
static Properties props = new Properties();
//加载驱动 放在静态代码块中 都可以使用
static {
try {
//把输入流装载到proper对象中 反射 把属性文件加载到流中 使用类装载器加载
props.load(JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.props"));
//获取proper中的数据key对应的value值 加载驱动类
Class.forName(props.getProperty("jdbc_driverClass"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//建立连接 静态方法直接调用
public static Connection getConnection() {
Connection conn =null;
try {
conn=DriverManager.getConnection(props.getProperty("jdbc_url"),
props.getProperty("jdbc_username"),
props.getProperty("jdbc_password"));
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//增删改 传参sql 和多个参数所以使用集合
public static int save(String sql ,Object[] params) {
int count =0;
// 获取连接
Connection conn = getConnection();
PreparedStatement ps =null ;
try {
ps = conn.prepareStatement(sql);
//判断参数是否为空 不为执行
if(params !=null) {
//循环遍历参数
for(int i=1;i<=params.length;i++) {
ps.setObject(i,params[i-1]);
}
}
// 执行成功返回1 执行失败返回0
count=ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//close(null,ps, conn);
}
return count;
}
//查询
public static ResultSet select(String sql ,Object[] params) {
ResultSet rs =null;
Connection conn = getConnection();
PreparedStatement ps =null ;
try {
ps = conn.prepareStatement(sql);
if(params !=null) {
for(int i=1;i<=params.length;i++) {
ps.setObject(i,params[i-1]);
}
}
rs =ps.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//close(null,ps, conn);
}
return rs;
}
//关闭连接
public static void close(ResultSet rs,PreparedStatement ps ,Connection conn) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps!=null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 测试程序是否正确
public static void main(String[] args) {
String sql ="select * from admin";
Object[] params = {};
ResultSet rs = select(sql,params);
try {
while(rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}