日期:2014-05-16  浏览次数:20374 次

使用JDBC对数据库进行CRUD的操作


   Jdbc中的statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。

  Statement对象的executeUpdate方法,用于向数据库发送增、删、改的sql语句,executeUpdate执行完后,将会返回一个整数(即增删改语句导致了数据库几行数据发生了变化)。

  Statement.executeQuery方法用于向数据库发送查询语句,executeQuery方法返回代表查询结果的ResultSet对象。

  CRUD操作-create

 

使用executeUpdate(String sql)方法完成数据添加操作,示例操作:

  Statement st = conn.createStatement();

 

String sql = "insert into user(….) values(…..) ";

 

int num =st.executeUpdate(sql);

 

if(num>0){

        System.out.println("插入成功!!!");

}

 

CRUD操作-updata

使用executeUpdate(String sql)方法完成数据添加操作,示例操作:

 

Statement st =conn.createStatement();

 

String sql = “update user set name=‘’ where name=‘’";

 

int num =st.executeUpdate(sql);

 

if(num>0){

        System.out.println(“修改成功!!!");

}

 

CRUD操作-delete

使用executeUpdate(String sql)方法完成数据删除操作,示例操作:

 

Statement st =conn.createStatement();

 

String sql = “delete from user where id=1;

 

int num =st.executeUpdate(sql);

 

if(num>0){

        System.out.println(“删除成功!!!");

}

 

CRUD操作-read

 

使用executeQuery(String sql)方法完成数据查询操作,示例操作:

Statement st =conn.createStatement();

 

String sql = “select * from user where id=1;

 

ResultSet rs =st.executeUpdate(sql);

 

while(rs.next()){

        //根据获取列的数据类型,分别调用rs的相应方法

        //映射到java对象中

}

 

 

防范sql注入攻击

 

SQL 注入是用户利用某些系统没有对输入数据进行充分的检查,从而进行恶意破坏的行为。

1、statement存在sql注入攻击问题,例如登陆用户名采用' or 1=1 or name='

2、防范 SQL 注入,需要采用PreparedStatement取代Statement。

 

PreperedStatement是Statement的孩子,它的实例对象可以通过调用Connection.preparedStatement()方法获得,相对于Statement对象而言:

?        PreperedStatement可以避免SQL注入的问题。

?        Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出。PreparedStatement 可对SQL进行预编译,从而提高数据库的执行效率。

?        并且PreperedStatement对于sql中的参数,允许使用占位符的形式进行替换,简化sql语句的编写。

 

数据库分页

 

MySQL分页的实现:

?        Select * from table limit M,N

?        M:记录开始索引位置

?        N:取多少条记录。

 

 

 对于数据库的CRUD操作是我们实现与数据库进行交互的最基本的操作,我们应当熟练、准确的使用它。