Mysql的JDBC

  Java程序可以通过JDBC链接数据库,通过JDBC可以方便的访问数据库,不必为特定的数据库编写专门的程序。

  需要先配置mysql-connector-java-5.0.8-bin.jar

  使用JDBC连接数据库的开发流程如下:

  1. 注册数据库驱动  Class.forName("com.mysql.jdbc.Driver");
  2. 构建数据库连接的URL,Mysql的连接URL为"jdbc:mysql://localhost:3306/test"
  3. 获取Connection对象,该对象是JDBC封装的数据库连接对象,只有创建此对象后,才可以对数据执行相关操作。DriverManager.getConnection(url, username, password);

     如下为JDBC核心API的五个接口:

例:mysql数据表格式:

增加操作的核心代码:

try{
    Class.forName("com.mysql.jdbc.Driver");
    String url="jdbc:mysql://localhost:3306/student";
    Connection con=DriverManager.getConnection(url, "root", "");
    String sql="insert into tb_books(name, price, bookCount, author) values(?,?,?,?)";
    PreparedStatement ps=con.prepareStatement(sql);
    ps.setString(1, book.getName());
    ps.setDouble(2, book.getPrice());
    ps.setInt(3, book.getBookCount());
    ps.setString(4, book.getAuthor());
    int row = ps.executeUpdate();
    if(row>0){
        out.print("成功添加"+row+"  行数据");
    }
    ps.close();
    con.close();
}
catch(Exception e){
    out.print("添加失败!");
    e.printStackTrace();
}

查询操作的核心代码:

        try{
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql://localhost:3306/student";
            Connection con=DriverManager.getConnection(url, "root", "");
            Statement statement=con.createStatement();
            String sql="select * from tb_books";
            ResultSet rs=statement.executeQuery(sql);
            ArrayList<Book> list=new ArrayList<Book>();
            while(rs.next()){
                Book book=new Book();
                book.setName(rs.getString("name"));
                book.setPrice(rs.getDouble("price"));
                book.setBookCount(rs.getInt("bookCount"));
                book.setAuthor(rs.getString("author"));
                list.add(book);
            }
            request.setAttribute("list", list);
            rs.close();
            con.close();
        } 
        catch(ClassNotFoundException e){
            e.printStackTrace();
        }
        catch(SQLException e){
            e.printStackTrace();
        }

修改数据的核心代码:

try{
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql://localhost:3306/student";
            Connection con=DriverManager.getConnection(url, "root", "");
            String sql="update tb_books set bookCount=? where name=?";
            PreparedStatement ps=con.prepareStatement(sql);
            ps.setInt(1, bookCount);
            ps.setString(2, name);
            ps.executeUpdate();
            ps.close();con.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }

对数据的其他操作类似。

      

原文地址:https://www.cnblogs.com/galway/p/4636269.html