zoukankan      html  css  js  c++  java
  • JDBC编程步骤

    1.注册驱动

    Class.forname("com.mysql.jdbc.Driver");

    2.获取链接

    Connection con=DriverManager.getConnection(url,user,password);

    3.创建statement对象

    Statement st=con.createment();

    4.发送sql并且执行

    ResultSet rs=st.executeQuery();

    5.遍历结果集

    while(rs.next){

      ...

    }

    6.释放资源,放在finally中

    案例:

    public static void main(String[] args) {
            
            //获取连接
            Connection con = null;
            //创建statement对象
            Statement statement = null;
            ResultSet rs = null;
            try {
                //1.注册驱动
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/day09", "root", "123");
                statement = con.createStatement();
                //发送并执行sql
                String sql = "select * from user";
                rs = statement.executeQuery(sql);
                //遍历
                while(rs.next()){
                    String id = rs.getString("id");
                    String name = rs.getString(2);
                    int age = rs.getInt(3);
                    System.out.println(id+"+++"+name+"++++"+age);
                }
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                //释放资源
                if(rs!=null){
                    try {
                        rs.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if(statement!=null){
                    try {
                        statement.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if(con!=null){
                    try {
                        con.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
  • 相关阅读:
    delphi利用qdac qworker计划任务
    delphi libssh2 无法立即完成一个非阻止性套接字操作
    线程池底层原理
    【spring源码分析】二、Spring扩展点的归总
    【spring源码分析】一、spring Refresh流程
    Spring中常用的类
    设计模式-proxy
    SpringAOP
    SpringIOC
    难受,nginx worker进程内存持续飘升!
  • 原文地址:https://www.cnblogs.com/lichangyun/p/8643259.html
Copyright © 2011-2022 走看看