Statementh和PreparedStatement的区别
- Statement主要用于执行静态SQL语句,即内容固定不变的SQL语句。Statement每执行一次都要对传入的SQL语句编译一次,效率较差。
- PreparedStatement 接口是 Statement 的子接口,它表示一条预编译过的 SQL语句。
- PreparedStatement是接口,继承自Statement接口。
- 使用PreparedStatement时,SQL语句已提前编译,三种常用方法 execute、 executeQuery 和 executeUpdate 已被更改,以使之在调用时无需再传入参数。
jdbc连接流程(主流)
1. 在项目src文件夹下新建/导入jdbc.properties
(数据库配置文件,为了方便后续修改数据库配置文件)。
2. 在lib文件夹内导入Jar(驱动包),并右键驱动包选择:Add as Library
(导入驱动包)
3. 导入工具类JdbcUtils
,以便调用其中的getConnection()
方法更便捷地连接配置文件内定义的数据库。
附:工具类中getconnection方法的详细实现
public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
Properties properties = new Properties();
InputStream in= JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");//src路径下
properties.load(in);
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
4. * a. 传入的参数 采用 占位符 ?
* b. setXXX():方法赋值
* c. setString(int parameterIndex, 参数) :parameterIndex为下标,从1开始。
例:
Connection con = null;//获取连接
PreparedStatement stat = null;//处理sql语句
ResultSet resultSet=null;//在查询中作为接收结果的集合
con = JdbcUtils.getConnection();//将数据库连接交给Collection
String sql = "insert into employees(*) values (?,?,?,?,?,?)";// 语句中的 ? 是占位符
stat = con.prepareStatement(sql);
//将带有占位符的语句交由PreparedStatement处理
stat.setString(1, emp.getFirstName());
// set方法给占位符赋值,第一个参数代表占位符下标,从1开始,第二个参数代表要替换占位符的语句\变量
stat.executeUpdate();
//sql *增删改* 语句使用 .executeUpdate()方法。
//由于查询语句需要返回值,所以使用 .executeQuery();方法 如:
resultSet = stat.executeQuery(); //调用executeQuery()方法,返回ResultSet集合,后续遍历输出即可。