一、基本步骤
注:组成包:java.sql.*;javax.sql.*;这两个包都包含在了JDK中。
1、把数据库的驱动加入到classpath中
2、开发步骤:
* 1、注册驱动
* 2、获取与数据库的链接
* 3、得到代表SQL语句的对象
* 4、执行语句
* 5、如果执行的是查询语句,就会有结果集,处理
* 6、释放占用的资源
二、封装工具类JdbcUtils
public class JdbcUtil {
private static String driverClass;
private static String url ;
private static String user;
private static String password;
static{
InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties p = new Properties();
try {
p.load(is);
} catch (IOException e) {
e.printStackTrace();
}
driverClass= p.getProperty("driverClass");
url = p.getProperty("url");
user = p.getProperty("user");
password = p.getProperty("password");
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 得到数据库连接
* @return
* @throws Exception
*/
public static Connection getConnection() throws Exception{
return DriverManager.getConnection(url,user,password);
}
/**
* 释放资源
* @param rs
* @param st
* @param con
*/
public static void release(ResultSet rs,Statement st,Connection conn){
if(rs!=null){
try{
rs.close();
}catch(Exception ex){
throw new RuntimeException(ex);
}
}
if(st!=null){
try{
st.close();
}catch(Exception ex){
throw new RuntimeException(ex);
}
}
if(conn!=null){
try{
conn.close();
}catch(Exception ex){
throw new RuntimeException(ex);
}
}
}
}
三、防注入(JDBC中的PreparedStatement)
public void saveData(User user) {
Connection connection = null;
PreparedStatement stmt = null;
try {
conn = JdbcUtils.getConnection();
stmt = connection.prepareStatement("insert into user (username,password,email,birthday) values (?,?,?,?)");
stmt.setString(1, user.getUsername());
stmt.setString(2, user.getPassword());
stmt.setString(3, user.getEmail());
stmt.setString(4, new Data()user.getBirthday().getTime());
stmt.executeUpdate();
} catch (Exception e) {
throw new RuntimeException()
} finally {
JdbcUtils.release(null,stmt,conn);
}
}