zoukankan      html  css  js  c++  java
  • 运用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     }
  • 相关阅读:
    学习pyyaml
    使用fabric2打包部署文件
    python之OS模块
    zabbix3.4.2安装
    格式化python代码
    ansible常用模块介绍
    TCP/IP 协议
    Python爬虫:使用正则表达式爬取网站电影信息
    解决python3爬取网页(GB2312编码)中文乱码问题
    我的第一个python爬虫:爬取豆瓣top250前100部电影
  • 原文地址:https://www.cnblogs.com/lingdu9527/p/11006443.html
Copyright © 2011-2022 走看看