JDBC编程常用接口

http://blog.csdn.net/fcrpg2005/article/details/657804

在 java.sql 这个包里面有几个常用的接口,在进行JDBC编程里面会经常用到。

Connection

Statement

PreparedStatement

CallableStatement

 1、Connection 接口,这个接口天天用,年年用,不用再说了。

2、Statement 接口。

在各个论坛上的文章里面,经常看到别人写的代码,都是很不规范,甚至存在安全隐患。

如:他们会这样写:

Statement stat = con.createStatement();

ResultSet rs = stat.executeQuery("select * from TabName where userName='"+userName+"'");

有的甚至将这些代码写在JSP页面中,另偶实在困惑。

如果要这样回变量,怎么不用PreparedStatement这个接口呢。

用到此接口时,最好直接写出完整的SQL语句:

如:ResultSet rs = stat.executeQuery("select * from TableName ");

如:ResultSet rs = stat.eecuteQuery("select count(*) from TableName");

3、PreparedStatement 接口,非常常用的接口。

用法:

PreparedStatement ps = con.prepareStatement(strSql);

strSql中的问号代码所传的参数,有几个就传几个。而且要对应相应的类型。

如:

String strSql = "select * from TableName where userName=? and password=?";

PreparedStatement ps = con.prepareStatement(strSql);

ps.setString(1,"xxxxxxxx");

ps.setString(2,"yyyyyyyy");

ResultSet rs = ps.executeQuery();

这个接口所传的SQL命令是预编译的,所以速度方面比Statement这个接口要快得多。

4、CallableStatement 接口。用来处理存储过程。

用法:

CallableStatement cs = con.prepareCall("{call 存储过程名(?,?,?...)}");

后面所还的括号是所传递的参数。如果没有则不用括号。

目前,大部份的JDBC编程都会用存储过程代替直接写SQL语句了。

如:

CallableStatement cs = con.prepareCall("{call prcSelectResult(?,?)}");

cs.setString(1,"TableName");

cs.setString(2,"*");

ResultSet rs = cs.executeQuery();

prcSelectResult的代码:

create proc prcSelectResult

@tabName varchar(50),

@colName varchar(50)

as

begin

    declare @strSql varchar(600)

    set @strSql = "select "+@colName+" from "+@tabName

    exec (@strSql)

end

当然,这只是一个简单的例子。

 可以看出,上面的几种数据库操作中,以存储过程方法最佳。因为存储过程在数据库中是预编译的,因此,他比PreparedStatement接口的预编译命令又高一筹。。

关于CallableStatement 接口和存储过程的介绍还会在以后的笔记中详细谈及。

原文地址:https://www.cnblogs.com/ttjava/p/3642960.html