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();
                    }
                }
            }
        }
  • 相关阅读:
    BZOJ1066: [SCOI2007]蜥蜴
    BZOJ1934: [Shoi2007]Vote 善意的投票
    BZOJ2321: [BeiJing2011集训]星器
    BZOJ1076: [SCOI2008]奖励关
    BZOJ1821: [JSOI2010]Group 部落划分 Group
    BZOJ3038: 上帝造题的七分钟2
    NOIP2017滚粗记
    BZOJ1087: [SCOI2005]互不侵犯King
    BZOJ1085: [SCOI2005]骑士精神
    BZOJ1295: [SCOI2009]最长距离
  • 原文地址:https://www.cnblogs.com/lichangyun/p/8643259.html
Copyright © 2011-2022 走看看