中,我们应该将最终必须要执行的代码放到finally当中
释放资源的代码
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
7. 防止 sql 注入
在 service 层进行逻辑判断
使用PreparedStatement对象
package cn.test.jdbc.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.Properties;
import com.mysql.jdbc.Driver;
public class JDBCDemo {
//连接数据库的url的写法
//jdbc主协议,mysql是子协议
//jdbc协议:数据库子协议://主机:端口号:/数据库名
private String url="jdbc:mysql://localhost:3306/day15";
//用户名
String username = "root";
//密码
String password = "Name-66437";
@Test
public void main(String [] args) throws SQLException{
//1.创建一个驱动程序的类对象
Driver driver = new com.mysql.jdbc.Driver();
//设置用户名和密码
Properties props = new Properties();
props.setProperty("username", username);
props.setProperty("password", password);
//2.连接数据库
Connection conn = driver.connect(url, props);
Statement stmt = conn.createStatement();
String sql = "select * from student";
ResultSet rs = stmt.executeQuery(sql);
//7.处理结果集
System.out.println("id | name | password | email | birthday");
while(rs.next()) {
// 有第一行
int id = rs.getInt("id"); // 通过列名取值比较直观
String name = rs.getString("name");
String psw = rs.getString("password");
String email = rs.getString("email");
Date birthday = rs.getDate("birthday");
System.out.println(id + " | " + name + " | " + psw + " | " + email + " | " + birthday);
}
//释放资源的代码
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
?