JDBC

来源:互联网 发布:程序员没前途 编辑:程序博客网 时间:2024/06/07 23:17

JDBC

JDBC中主要的接口(类)

  • DriverManager
    使用DriverManager的getConnection()方法即可。

  • Connection
    最重要的方法就是获取 statement
    Statement statement =getConnection().createStatement();//3.获取statemet

  • Statement
    用来执行sql语句

  • ResultSet
    表示结果集,是一个二维的表格

开发步骤

  1. 注册驱动
  2. 获得连接
  3. 获得sql语句执行者
  4. 执行sql语句
  5. 处理结果
  6. 释放资源
    public static Connection getConnection() throws Exception {        Class.forName("com.mysql.jdbc.Driver"); //1.注册驱动        String url ="jdbc:mysql//localhost:3036/table";        Connection connection = DriverManager.getConnection(url, "user", "password"); //2.获取链接        return connection;    }    public void inserct() throws Exception {        Statement statement =getConnection().createStatement();//3.获取statemet        String sql =" select * from db"; //4.sql语句        ResultSet result =statement.executeQuery(sql);//执行        while (result.next()) {            //todo        }           }   
  • 关闭
    与IO流一样,使用后的东西都要关闭,关闭顺序是先得到后关闭,后得到先关闭
    result.close();
    statement.close();
    connection.close();
原创粉丝点击