0
点赞
收藏
分享

微信扫一扫

JDBC概述

外贸达人小峻先森 2022-01-12 阅读 60

1. 原理

2. JDBC编写步骤

  1. 注册驱动 --加载Driver类
  2. 获取连接–得到Connetion类
  3. 执行增删改查–发送SQL给 Mysql执行
  4. 释放资源–关闭相关连接
		Class.forName("com.mysql.cj.jdbc.Driver");//加载驱动,自动注册Driver
        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);//获取连接
        //3.操作数据库,实现增删改查
        Statement stmt = conn.createStatement();//Statement对象可对表进行增删改查

3. 表的增删改查

	//删除
	static public void delete(Connection conn) throws SQLException {
        String s="delete from stu where sno = '01'";
        PreparedStatement ptmt=conn.prepareStatement(s);
        ptmt.execute();
    }
    //添加
    static public void add(Connection conn) throws SQLException {
        Statement stmt = conn.createStatement();
        String sql="insert into stu values('02','秋婷')";
        String sql2="insert into stu values('03','世枫')";
        stmt.executeUpdate(sql);
        stmt.executeUpdate(sql2);
    }
    //更新
    static public void update(Connection conn) throws SQLException {
        Statement stmt = conn.createStatement();
        String sql="update  stu set sno ='01' where sname = '秋婷'";
        String sql2="update  stu set sno ='02' where sname = '世枫'";
       // stmt.executeBatch();
        stmt.executeUpdate(sql);
        stmt.executeUpdate(sql2);
    }
    //查询
    static public void research(Connection conn) throws SQLException {
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("select * from stu where sno = '01'");
        while(rs.next()){
            System.out.println(rs.getString(1  )+" "+rs.getString(2));
        }
    }
    //输出
    static void info(Connection conn) throws SQLException {
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM stu");
        //如果有数据,rs.next()返回true
        while(rs.next()){
            System.out.println(rs.getString(1  )+" "+rs.getString(2));
        }
    }
举报

相关推荐

0 条评论