软件设计——单例模式应用

//方法
1、利用构造函数或单例初始化函数,实现数据库的连接
2、提供通用查询函数(接受SELECT操作)
3、提供通用的插入函数(接受INSERT操作)
4、提供通用的修改函数(接受UPDATE操作)
5、提供通用的删除函数(接受DELETE操作)
6、利用析构函数或单例销毁函数,实现数据库的关闭(JAVA使用 finalize)

public class JDBCDemo {
 public static void update(){//增删改
  Connection connection = null;
  Statement stmt = null;
  try {
  //导入驱动,加载具体的驱动类 
  Class.forName("com.mysql.cj.jdbc.Driver");//加载具体的驱动类
  //与数据库建立连接
  connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?serverTimezone=GMT%2B8","用户名","密码");
  //创建表名称为student,分别创建字段:stuno,stuname,stuage,gname
  //发送sql,执行(增删改)
  stmt = connection.createStatement();
  String sql = "insert into student values(2,'ls',20,'rg8')";
//  String sql = "update student set STUAGE=21 where stuno=1";
//  String sql = "delete from student where stuno=1";
  //执行sql(增删改executeUpdate)
  int count = stmt.executeUpdate(sql);//返回值表示增删改几条数据
  //处理结果
  if(count>0) {
   System.out.print("操作成功!");
  }
  }catch(ClassNotFoundException e){
   e.printStackTrace();
  }catch(SQLException e){
   e.printStackTrace();
  }catch(Exception e){
   e.printStackTrace();
  }finally {
   try {
    if(stmt!=null)stmt.close();//对象.方法
    if(connection!=null)connection.close();
   }catch(SQLException e){
    e.printStackTrace();
   }
  }
 }
 public static void query() {
 Connection connection = null;
 Statement stmt = null;
 ResultSet rs = null;
 try {
 //导入驱动,加载具体的驱动类 
 Class.forName("com.mysql.cj.jdbc.Driver");//加载具体的驱动类
 //与数据库建立连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?serverTimezone=GMT%2B8","用户名","密码");
 //发送sql,执行(查)
 stmt = connection.createStatement();
// String sql = "select stuno,stuname from student";
// String sql = "select * from student";
 String sql = "select * from student where stuname like '%l%'";
 //执行sql(查询executeQuery)
 rs = stmt.executeQuery(sql);//返回值表示增删改几条数据
 //处理结果
 while(rs.next()) {
  int sno =rs.getInt("stuno");
  String sname =rs.getString("stuname");
//  int sno =rs.getInt(1);//下标:从1开始计数
//  String sname =rs.getString(2);
  System.out.println(sno+"--"+sname);
 }
 }catch(ClassNotFoundException e){
  e.printStackTrace();
 }catch(SQLException e){
  e.printStackTrace();
 }catch(Exception e){
  e.printStackTrace();
 }finally {
  try {
   if(rs!=null)rs.close();
   if(stmt!=null)stmt.close();//对象.方法
   if(connection!=null)connection.close();
  }catch(SQLException e){
   e.printStackTrace();
   }
  }
 }
 public static void main(String[] args) {
//  update();
  query();
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值