package DB;
import java.sql.*;
public class DBHelper {
//1.判断驱动 连接驱动
//2.连接数据库
//3.创建对象执行SQL语句
//4.接收执行过后的返回值
// //5.释放资源
static { //类加载的时候执行, 整个程序只会执行一次
//1. 连接驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("驱动打开失败");
}
}
private static Connection con=null;//全局静态变量
public static void GetConnection()
{
//2.连接数据库
String url="jdbc:mysql://localhost:3306/bookmanagesys";
try {
con=DriverManager.getConnection(url,"root","123456");
} catch (SQLException e) {
System.out.println("数据库连接失败");
}
}
//通用查询方法
public static ResultSet Query(String sql)
{
try{
GetConnection();//连接数据库方法
Statement st=con.createStatement();//创建一个对象用于执行SQL
//查询语句执行的方法 返回值是 ResultSet结果集
//4.返回执行结果
ResultSet rs=st.executeQuery(sql);
return rs;
}catch (SQLException e)
{
System.out.printf(e.getMessage());
}finally {
//5.释放资源
// if(con!=null){
// try {
// con.close();
// }catch (SQLException ex)
// {
// throw new RuntimeException(ex);
// }
// }
}
return null;
}
// public static void main(String[] args) {
// //1. 连接驱动
// try {
// Class.forName("com.mysql.cj.jdbc.Driver");
// } catch (ClassNotFoundException e) {
// System.out.println("驱动打开失败");
// }
// //2.连接数据库
// String url="jdbc:mysql://localhost:3306/bookmanagesys";
// Connection con=null;
// try {
// con=DriverManager.getConnection(url,"root","123456");
// } catch (SQLException e) {
// System.out.println("数据库连接失败");
// }
// //3.创建对象执行SQL语句
// /*******查询*************/
// /* try {
// String sql="select *from user";
// Statement st=con.createStatement();//创建一个对象用于执行SQL
// //查询语句执行的方法 返回值是 ResultSet结果集
// //4.返回执行结果
// ResultSet rs= st.executeQuery(sql);
// System.out.println("编号\t\t姓名\t\t密码");
// while (rs.next())//读取 rs对象的下一个元素
// {
// //循环取每一条数据
// long id= rs.getLong("id");
// String name= rs.getString("username");
// String password= rs.getString("password");
// System.out.printf("%d\t\t%s\t\t%s\n",id,name,password);
// }
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }finally {
// //5.释放资源
// if(con!=null){
// try {
// con.close();
// }catch (SQLException ex)
// {
// throw new RuntimeException(ex);
// }
// }
// }*/
// /*******增删改*************/
// String sql="insert into user(username,password) values(?,?)";
// try {
// //PreparedStatement 继承于Statement
// //PreparedStatement是Statement的子类
// //3.添加需要执行的sql语句
// PreparedStatement pre=con.prepareStatement(sql);
// //添加参数
// pre.setString(1,"张三");
// pre.setString(2,"123456");
// //执行SQL 语句
// //executeUpdate 返回值为int类型 是执行语句后受影响的行数
// int row= pre.executeUpdate();//这个方法执行增删改的语句 4. 得到返回值
// if(row>0)
// {
// System.out.println("执行成功");
// }else {
// System.out.printf("执行失败");
// }
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// }
}