一、Statement
Statement用于执行不带参数的简单SQL语句,并返回它所生成结果的对象,每次执行SQL语句时,数据库都要编译该SQL语句。如下所示:
Statement stmt = conn.getStatement();
stmt.executeUpdate("SELECT topic,title from question_content");
二、PreparedStatement
PreparedStatement表示预编译的SQL语句的对象,用于执行带参数的预编译SQL语句。如下所示:
package connection;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ConnectionDemo01 {
//定义MySQL数据库的驱动程序
public static final String DBDRIVER = "com.mysql.cj.jdbc.Driver";
//定义MySQL数据库的连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/englishlearning20171109?serverTimezone=GMT";
//MySQL数据库的连接用户名
public static final String DBUSER = "root";
//MySQL数据库的连接密码
public static final String DBPASS = "123456";
public static void main(String[] args) throws IOException {
Connection conn = null;//数据库连接
PreparedStatement ps = null;
String sql = "SELECT topic,title from question_content";
String content = null;
String topic = null;
OutputStreamWriter out = null;
try {
//加载驱动程序
Class.forName(DBDRIVER);
}catch(ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
//创建预编译SQL对象
ps = conn.prepareStatement(sql);
//执行SQL,获取结果集rs
ResultSet rs = ps.executeQuery();
//处理结果集
while(rs.next()) {
topic = rs.getString("topic");
content = rs.getString("title");
out = new OutputStreamWriter(new FileOutputStream("E://File_jieba/content.txt", true),"UTF-8");
out.write(content + "\n");
out.flush();
}
}catch(SQLException e) {
e.printStackTrace();
}
System.out.println(conn);
try {
out.close();
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
虽然Statement与PreparedStatement对象能够完成相同的功能,但与Statement相比,PreparedStatement具有以下优点:
(1)效率更高。
(2)代码可读性和可维护性更好。
(3)安全性更好。
三、CallableStatement
CallableStatement则提供了用来调用数据库中存储过程的接口,如果有输出参数要注册,说明是输出参数。CallableStatement由prepareCall()方法所创建,它为所有的DBMS(数据库管理系统)提供了一种以标准形式调用已存储过程的方法。它从PreparedStatement中继承了用于处理输入参数的方法,而且还增加了调用数据库中的存储过程和函数以及设置输出类型参数的功能。
四、Statement与PreparedStatement的区别
1、PreparedStatement⽀持动态设置参数,Statement不⽀持。
2、PreparedStatement可避免如类似 单引号 的编码⿇烦,Statement不可以。
3、PreparedStatement⽀持预编译,Statement不⽀持。
4、在sql语句出错时PreparedStatement不易检查,⽽Statement则更便于查错。
5、PreparedStatement可防⽌Sql注入,更加安全,⽽Statement不⾏。