zoukankan      html  css  js  c++  java
  • JDBC基础知识

    常见连接数据库工具:

    1. 图形化工具:点击、拖拽就可以操作数据库,对用户友好,简单对数据操作,复杂数据库操作爱莫能助
    2. JDBC(驱动程序):调用jar包接口
    3. 窗口(命令行):输入完整SQL语句对复杂数据库查询

    JDBC:在java中就是jar包,应用通过JDBC提供的统一接口就可以实现对不同数据库(ORACLE、Mysql)的使用,让我们不需要了解他们之间的差异与具体操作。

     Connection对象:代表java应用程序对后端数据库的一条物理链接,基于链接执行sql语句

    Statement stmt=conn.createStatement();

    Statement对象:是sql的容器,通过executeQuery承载sql语句,进行增删改查,返回ResultSet对象/int。

    ResultSet rs=stmt.executeQuery("select name from student");

    ResultSet对象:代表查询的结果

    获取行:

      .next():向后移动一行

      .previous():向前移动一行

      .absolute():直接移动到某一行

    获取列:

      .getString(ColumnName/Index)

      .getInt(ColumnName/Index)

      .getObject(ColumnName/Index)

    package com.tao.test;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class jdbctest {
    
        static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        static final String DB_URL = "jdbc:mysql://localhost:3306/schoolweb?useUnicode=true&characterEncoding=UTF-8";
        static final String USER = "root";
        static final String PASSWORD = "admin";
    
        public static void main(String[] args) throws ClassNotFoundException {
            Connection conn = null;
            Statement stmt = null;
            ResultSet rs = null;
    
            // 装载驱动程序
            Class.forName(JDBC_DRIVER);
            // 建立数据库连接
            try {
                conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
                // 执行sql语句
                stmt = conn.createStatement();
                rs = stmt.executeQuery("select name from student");
                // 获取执行结果
                while (rs.next()) {
                    System.out.println(rs.getString("name"));
                }
            } catch (SQLException e) {
                // 异常处理
                e.printStackTrace();
            } finally {
                //释放宝贵资源
                try {
                    if (conn != null) {
                        conn.close();
                    }
                    if (stmt != null) {
                        stmt.close();
                    }
                    if (rs != null) {
                        rs.close();
                    }
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    JDBC进阶:java程序运行在JVM中,JVM也有内存。

    1.查询结果条目过多,防止内存溢出,一次载入较少记录。

    游标:提供一种客户端读取部分结果集的机制,分批读取。

      1.在DB_URL中设置useCursorFetch=true开启游标

       2.使用setFetchSize()设置每次读多少

    package com.tao.test;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class jdbctest {
    
        static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        static final String DB_URL = "jdbc:mysql://localhost:3306/schoolweb?useCursorFetch=true&useUnicode=true&characterEncoding=UTF-8";
        static final String USER = "root";
        static final String PASSWORD = "admin";
    
        public static void main(String[] args) throws ClassNotFoundException {
            Connection conn = null;
            PreparedStatement ptmt=null;
            ResultSet rs = null;
    
            // 装载驱动程序
            Class.forName(JDBC_DRIVER);
            // 建立数据库连接
            try {
                conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
                // 执行sql语句
                ptmt = conn.prepareStatement("select name from student");
                ptmt.setFetchSize(1);//每次读取一条记录
                rs=ptmt.executeQuery();
                // 获取执行结果
                while (rs.next()) {
                    System.out.println(rs.getString("name"));
                }
            } catch (SQLException e) {
                // 异常处理
                e.printStackTrace();
            } finally {
                //释放宝贵资源
                try {
                    if (conn != null) {
                        conn.close();
                    }
                    if (ptmt != null) {
                        ptmt.close();
                    }
                    if (rs != null) {
                        rs.close();
                    }
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    2.一行存储大字段内容,比如存储博文,怎么读取?

      1.流方式读取,按区间读取

    package com.tao.test;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    public class jdbctest {
    
        static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        static final String DB_URL = "jdbc:mysql://localhost:3306/schoolweb?useCursorFetch=true&useUnicode=true&characterEncoding=UTF-8";
        static final String USER = "root";
        static final String PASSWORD = "admin";
        static final String FILE_URL = "./text.txt";
    
        public static void main(String[] args) throws ClassNotFoundException,
                IOException {
            Connection conn = null;
            PreparedStatement ptmt = null;
            ResultSet rs = null;
    
            // 装载驱动程序
            Class.forName(JDBC_DRIVER);
            // 建立数据库连接
            try {
                conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
                // 执行sql语句
                ptmt = conn.prepareStatement("select name from student");
                ptmt.setFetchSize(1);// 每次读取一条记录
                rs = ptmt.executeQuery();
                // 获取执行结果
                while (rs.next()) {
                    InputStream in = rs.getBinaryStream("name");
                    File f = new File(FILE_URL);
                    FileOutputStream out = new FileOutputStream(f);
                    int temp = 0;
                    while ((temp = in.read()) != -1)
                        out.write(temp);
                    out.close();
                    in.close();
                }
            } catch (SQLException e) {
                // 异常处理
                e.printStackTrace();
            } finally {
                // 释放宝贵资源
                try {
                    if (conn != null) {
                        conn.close();
                    }
                    if (ptmt != null) {
                        ptmt.close();
                    }
                    if (rs != null) {
                        rs.close();
                    }
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

     3.一次插入多条数据

      1.批处理Statement  

        addBatch()     //将sql打包为Batch

        executeBatch()   //执行sql

        clearBatch()     //清空Batch

    package com.tao.test;
    
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class jdbctest {
    
        static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        static final String DB_URL = "jdbc:mysql://localhost:3306/schoolweb?useCursorFetch=true&useUnicode=true&characterEncoding=UTF-8";
        static final String USER = "root";
        static final String PASSWORD = "admin";
        static final String FILE_URL = "./text.txt";
        static final String[] users = {"张三","李四"};
    
        public static void main(String[] args) throws ClassNotFoundException,
                IOException {
            Connection conn = null;
            Statement stmt = null;
            ResultSet rs = null;
    
            // 装载驱动程序
            Class.forName(JDBC_DRIVER);
            // 建立数据库连接
            try {
                conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
                // 执行sql语句
                stmt=conn.createStatement();
                for(String user:users)
                {
                    stmt.addBatch("insert into student(name) values('"+user+"')");
                }
                stmt.executeBatch();
                stmt.clearBatch();
            } catch (SQLException e) {
                // 异常处理
                e.printStackTrace();
            } finally {
                // 释放宝贵资源
                try {
                    if (conn != null) {
                        conn.close();
                    }
                    if (stmt != null) {
                        stmt.close();
                    }
                    if (rs != null) {
                        rs.close();
                    }
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    4.中文问题

      数据库: 实例、dabase、表、字段 级别内置编码(优先级从小到大)

      JDBC编码:DB_URL+characterEncoding=utf-8

  • 相关阅读:
    为什么选择 Yeoman 及 Yeoman 的安装
    NPOI高效匯出Excel
    CentOS7 MongoDB安裝
    打印函数调用堆栈
    libevent源码分析:eventop
    libevent源码分析:time-test例子
    libevent源码分析:event_assign、event_new
    libevent源码分析:bufferevent
    lievent源码分析:evbuffer
    epoll实现压测工具
  • 原文地址:https://www.cnblogs.com/handsometaoa/p/14257914.html
Copyright © 2011-2022 走看看