使用PrepareStatement预编译Statement
import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 使用preparedStatement预编译statement,可以是sql语句灵活化
* @author 可敢离我近点
*
*/
public class TestPreparedStatement {
public static void main(String[] args) {
/**
* 如果需要在finally块中手动关闭,就需要在try外声明
* 如果想要让其自动的关闭,则可以在try后面加一个括号初始化
* 先关闭statement,后关闭connection
* resultset结果集不需要手动关闭,他会在你关闭statement时自动的关闭
*/
Connection con=null;
PreparedStatement ps = null;
//初始化驱动
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("数据库驱动加载成功...");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xust?useUnicode=true&characterEncoding=utf-8&useSSL=false","root","mysql");
System.out.println("数据库连接成功...."+con);
String sql ="select * from area where id= ?;";
ps = con.prepareStatement(sql);
ps.setInt(1, 1);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
//字段的顺序从1开始,可以根据字段顺序访问
//也可以根据字段的名称访问数据
System.out.println(rs.getString(2)+"......"+rs.getInt("style"));
}
System.out.println("ok............");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if (null!=ps) {
ps.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (null!=con) {
con.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("yes.............");
}
}
}
优点:提高灵活性、运行更快、防止SQL注入