JDBC

来源:互联网 发布:奥登nba健康数据 编辑:程序博客网 时间:2024/06/17 12:18

1 . jdbc入门
1.JDBC简介?
1.1 java database connectivity :java数据库连接
1.2 sun公司提供两个一套规范
1.3 图文表示
2.JDBC用途(作用)
java程序连接数据库访问数据库中所有数据
3.使用的前提条件(准备工作)
3.1 java mysql技术、
3.2 jdk 安装正确(Path,classpath,javahome)
3.3 数据库安装成功
3.4 驱动下载:地址:http://mvnrepository.com/artifact/mysql/mysql-connector-java
4 .JDBC连接

@Test    public void  test03() throws Exception {        Class.forName("com.mysql.jdbc.Driver");        String url="jdbc:mysql://localhost:3306/1713_day03?user=root&password=123&useUnicode=true&characterEncoding=utf-8";        Connection con =  DriverManager.getConnection(url);        Statement statement = con.createStatement();        String sql="select * from user";        //ResultSet结果集:都是行和列组成的一个虚拟表集合        ResultSet resultSet =  statement.executeQuery(sql);        List<User> list =new ArrayList<>();        while (resultSet.next()) {             User user =new User();            int id = resultSet.getInt("id");             user.setId(id);            String name =resultSet.getString("name");            user.setName(name);            String pwd  = resultSet.getString("password");            user.setPwd(pwd);            String time =  resultSet.getString("loginTime");            user.setTime(time);           list.add(user);        }        //关闭资源        resultSet.close();        statement.close();        con.close();        System.out.println(list);    }

需要注意的点:

  1. 注册驱动代码;
  2. 网络地址格式是:http://www.baidu.com/内容
    端口默认80 ,可以省略
    则总结格式为:支持的协议://主机名(域名,ip地址):端口号/内容
    所以jdbc的url是: jdbc:mysql://localhost:3306/1713_day03
    ( 1713_day03是数据库名称 )
  3. boolean flag = statement.execute(sql);和代码中
    ResultSet resultSet = statement.executeQuery(sql);的区别.
    前者:为查询语句时,是true,其他是false
    后者:ResultSet结果集:都是行和列组成的一个虚拟表集合,是数据库表中的记录集合.

  4. 若 DriverManager.getConnection()的参数为三个时,可以利用下面的格式.
    String url = “jdbc:mysql://localhost:3306/1713_day03”;
    Connection connection = DriverManager.getConnection(url, “root”, “123”);

原创粉丝点击