• 运用jdbc连接数据库


    运用jdbc连接数据库可以分为六步:

    1、加载驱动

    2、创建连接

    3、创建语句

    4、执行语句

    5、处理返回结果

    6、关闭资源

    注意:导入包的时候要导入sql下的包不要jdbc下的

     1 private static void jdbc() throws ClassNotFoundException, SQLException {
     2         String driver="com.mysql.jdbc.Driver";
     3         String url = "jdbc:mysql://localhost:3306/mydata?useUnicode=true&characterEncoding=UTF-8";
     4         //mydata:是数据库名  ?和后面的语句是设置编码为UTF-8
     5         String user = "root";
     6         String password="1234";
     7         //1、加载驱动
     8         Class.forName(driver);
     9         //2、创建连接 
    10         Connection conn = DriverManager.getConnection(url, user, password);
    11         //3、创建语句
    12         String sql = "select * from t_book";
    13         PreparedStatement ps = conn.prepareStatement(sql);
    14         //4、执行语句
    15         ResultSet rs = ps.executeQuery();
    16         //5、处理结果
    17         List<Book> list = new ArrayList<>();
    18         while (rs.next()) {
    19             Book book = new Book(rs.getInt("bid"), rs.getString("bname"), rs.getDouble("bprice"),
    20                     rs.getDate("bdate"), rs.getString("btext"));
    21             list.add(book);
    22         }
    23         //6、关闭资源(后打开的资源要先关闭)
    24         rs.close();
    25         ps.close();
    26         conn.close();
    27     }
  • 相关阅读:
    bzoj3884: 上帝与集合的正确用法(数论)
    洛谷10月月赛R2·浴谷八连测R3题解
    bzoj5055: 膜法师(BIT)
    bzoj2213: [Poi2011]Difference(思维题)
    bzoj1016: [JSOI2008]最小生成树计数(kruskal+dfs)
    一模 (2) day2
    一模 (2) day1
    Prime Palindromes
    常州培训 day5 解题报告
    一模 (1) day2
  • 原文地址:https://www.cnblogs.com/lingdu9527/p/11006443.html
Copyright © 2020-2023  润新知