JavaWeb----JDBC

来源:互联网 发布:富云软件科技有限公司 编辑:程序博客网 时间:2024/05/20 02:21

一、JDBC的介绍
它是JAVA数据库连接的一种连接数据库的API。对不同的数据库采用统一的API进行编程。

二、接口:

DriverManager:驱动程序管理类,用来管理驱动Connection:连接指定的数据库Statement:执行sql语句,获取结果PreparedStatement:执行预编译的sql语句ResultSet:对结果集进行处理的方法

三、使用MySql数据库
1.在MySql的官网上下载mysql对应的jdbc驱动

编写JDBC的步骤:
加载驱动—打开连接—执行查询—-处理结果—清理环境。

2.加载驱动:首先将下载的mysql-jdbc lib拷入到项目中。
3.打开连接 执行语句 处理结果 清理环境

public class LoginDao {    Connection connection = null;    Statement statement = null;    ResultSet resultSet = null;/*  public boolean login(String username, String password) {    boolean flag = true;        String sql = "select * from login where username=?" + username                + "and password=?" + password;        return flag;    }*/    public boolean test() {        boolean flag = true;        String sql = "SELECT * FROM login";        try {            Class.forName("com.mysql.jdbc.Driver");// 反射Driver类上            connection = (Connection) DriverManager.getConnection(                    "jdbc:mysql://localhost:3306/test", "root", "123456");            statement = (Statement) connection.createStatement();            resultSet = statement.executeQuery(sql);            while (resultSet.next()) {               System.out.println(resultSet.getString("username"));            }        } catch (Exception e) {            // TODO: handle exception        } finally {            try {                if (resultSet != null)                    resultSet.close();            } catch (SQLException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            try {                if (statement != null)                    statement.close();            } catch (SQLException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            try {                if (statement != null) {                    connection.close();                }            } catch (SQLException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        return flag;    }    public static void main(String[] args) {        System.out.println(new LoginDao().test());    }}
0 0