• JDBC (29)


    1、JDBC:就是一套API,由sun公司定义类或者定义的接口。(全称 java database connectivity:Java访问数据库的标准规范),Java提供访问数据库规范称为JDBC,而生产厂商提供规范的实现类称为驱动。

    2、预处理对象executeUpdate方法,作用:完成记录的insertupdatedelete语句的执行。操作格式统一如下:

             1. 注册驱动

             2. 获取连接

             3. 获取预处理对象

             4. SQL语句占位符设置实际参数

             5. 执行SQL语句

             6. 释放资源

     注:Statement stat = con.createStatement();//createStatement 创建语句  //statement接口实现类,执行sql语句,返回结果集,PrepareStatement是其子接口(高效,防止sql attack)。接口和实现类都是数据库驱动里的东西。


    3、插入记录:insert     // 实现向分类表中插入指定的新分类

    public void demo01() throws Exception {
            // 1注册驱动,利用反射技术,将驱动加入内存
            Class.forName("com.mysql.jdbc.Driver"); // driverName:驱动程序的名称
            // 2获取连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", 
    "root");
    
            // 3获得预处理对象
    
            String sql = "insert into sort(sname) values(?)";
    
            PreparedStatement stat = conn.prepareStatement(sql);  // 解决SQL注入攻击问题
    
            // 4 SQL语句占位符设置实际参数
    
            stat.setString(1, "奢侈品");
    
            // 5执行SQL语句
    
            int line = stat.executeUpdate(); //执行更新,返回值是更新的条数
    
            System.out.println("新添加记录数:" + line);
    
            // 6释放资源
    
            stat.close();
    
            conn.close();
    
        }

    4、更新记录:update    // 实现更新分类表中指定分类ID所对应记录的分类名称

    public void demo02() throws Exception {
            // 1注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2获取连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
            // 3获得预处理对象中
            String sql = "update sort set sname=? where sid=?";
            PreparedStatement stat = conn.prepareStatement(sql);
            // 4 SQL语句占位符设置实际参数
            stat.setString(1, "数码产品");
            stat.setInt(2, 1);
    // 5执行SQL语句
            int line = stat.executeUpdate();
            System.out.println("更新记录数:" + line);
            // 6释放资源
            stat.close();
            conn.close();
        }

     5、删除记录:delete    //  实现删除分类表中指定分类ID的记录

        public void demo03() throws Exception {
            // 1注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2获取连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
            // 3获得预处理对象
            String sql = "delete from sort where sid=?";
            PreparedStatement stat = conn.prepareStatement(sql);
            // 4 SQL语句占位符设置实际参数  <不懂>
            stat.setInt(1, 1);
         // 5执行SQL语句
            int line = stat.executeUpdate();
            System.out.println("删除记录数:" + line);
            // 6释放资源
            stat.close();
            conn.close();
        }

    6、预处理对象executeQuery方法  ,作用:完成记录的select语句的执行。操作格式统一如下:

             1. 注册驱动

             2. 获取连接

        3. 获取预处理对象

        4. SQL语句占位符设置实际参数

        5. 执行SQL语句

             6. 释放资源


    7、 查询记录:select   //  实现查询分类表所有记录

    public void demo04() throws Exception {
            // 1注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2获取连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
            // 3获得预处理对象
            String sql = "select * from sort";
            PreparedStatement stat = conn.prepareStatement(sql);
            // 4 SQL语句占位符设置实际参数
          // 5执行SQL语句
            ResultSet rs = stat.executeQuery();
            // 6处理结果集(遍历结果集合)
            while( rs.next() ){
                //获取当前行的分类ID
                String sid = rs.getString("sid");//方法参数为数据库表中的列名
                //获取当前行的分类名称
                String sname = rs.getString("sname");
                //显示数据
                System.out.println(sid+"-----"+sname);
            }
            // 7释放资源
            rs.close();
            stat.close();
            conn.close();
        }

    8、查询记录:实现查询分类表中指定分类名称的记录

    public void demo05() throws Exception {
            // 1注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2获取连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root",
    "root");
            // 3获得预处理对象
            String sql = "select * from sort where sname=?";
            PreparedStatement stat = conn.prepareStatement(sql);
            // 4 SQL语句占位符设置实际参数
            stat.setString(1, "奢侈品");
         // 5执行SQL语句
            ResultSet rs = stat.executeQuery();
            // 6处理结果集(遍历结果集合)
            while( rs.next() ){
                //获取当前行的分类ID
                String sid = rs.getString("sid");//方法参数为数据库表中的列名
                //获取当前行的分类名称
                String sname = rs.getString("sname");
                //显示数据
                System.out.println(sid+"-----"+sname);
            }
            // 7释放资源
            rs.close();
            stat.close();
            conn.close();
        }

     9、JDBC工具类:获得数据库连接”操作,将在以后的增删改查所有功能中都存在,可以封装工具类JDBCUtils。提供获取连接对象的方法,从而达到代码的重复利用。

    该工具类提供方法:public static Connection getConn ()。代码如下:

    /*
     * JDBC工具类
     */
    public class JDBCUtils {
        public static final  String DRIVERNAME = "com.mysql.jdbc.Driver";
        public static final  String URL = "jdbc:mysql://localhost:3306/mydb";
        public static final  String USER = "root";
        public static final  String PASSWORD = "root";
    
        static {
            try {
                Class.forName(DRIVERNAME);
            } catch (ClassNotFoundException e) {
                System.out.println("数据库驱动注册失败!");
            }
        }
        //提供获取连接的方法
        public static Connection getConn() throws Exception {
            // 2. 获得连接
            Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
            // 返回连接
            return conn;
        }
    }

    10、 创建使用properties配置文件   (4个参数:驱动、URL、用户名、密码)  作用:方便后期维护,程序如果需要更换数据库,只需要修改配置文件即可。

    #文件:db.properties

    driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mydb user=root password=root

    11、加载配置文件:Properties对象 

     // 对应properties文件处理,开发中也使用Properties对象进行。我们将采用加载properties文件获得流,然后使用Properties对象进行处理。

       //  JDBCUtils.java中编写代码

    public class JDBCUtils {
    
        private static String driver;
        private static String url;
        private static String user;
        private static String password;
        // 静态代码块
        static {
            try {
                // 1 使用Properties处理流
                // 使用load()方法加载指定的流
                Properties props = new Properties();
                Reader is = new FileReader("db.properties");
                props.load(is);
                // 2 使用getProperty(key),通过key获得需要的值,
                driver = props.getProperty("driver");
                url = props.getProperty("url");
                user = props.getProperty("user");
                password = props.getProperty("password");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        /**
         * 获得连接
         */
        public static Connection getConnection() {
            try {
                // 1 注册驱动
                Class.forName(driver);
                // 2 获得连接
                Connection conn = DriverManager.getConnection(url, user, password);
                return conn;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

     12、使用JDBCUtils工具类

    //  测试类

    public class Demo {
        @Test
        public void insert(){
            try{
                //1,获取连接对象
                Connection conn = JDBCUtils.getConnection();
                //2,指定要执行的SQL语句
                String sql = "INSERT INTO zhangwu(name,money,parent) VALUES(?,?,?)";
                //4,获取SQL语句的执行对象 PreparedStatement
                PreparedStatement ppstat = conn.prepareStatement(sql);
                //5,执行SQL语句
                ppstat.setString(1, "股票收入");
                ppstat.setDouble(2, 5000);
                ppstat.setString(3, "收入");
                int line = ppstat.executeUpdate();
                //6,处理结果集
                System.out.println("line=" + line);
                //7,关闭连接
                ppstat.close();
                conn.close();
            } catch(SQLException e){
                throw new RuntimeException(e);
            }
        }
    }
  • 相关阅读:
    svn的revert、checkout、clean up、setting
    jsonp跨域原理
    王亚伟北大演讲:一切通胀问题都是货币问题(全文)
    string <-> wstring
    点在多边形内 经典算法(转)
    不可不表的OSG智能指针之强指针与弱指针 《转载》
    一个shell脚本给客户使用服务器生成一个序列号
    Rsync(远程同步): linux中Rsync命令的实际示例
    一个 rsync同步文件脚本
    用UltraISO制作CentOS U盘安装盘
  • 原文地址:https://www.cnblogs.com/ivan5277/p/10074480.html
Copyright © 2020-2023  润新知