mysql学习12( Statement对象 及 jdbc工具类 )
-
Statement对象:
-
jdbc中的Statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可;
-
Statement对象的executeUpdate方法,用于向数据库发送增,删,改的SQL语句,executeUpdate执行完后,将会返回一个整数(即数据库执行的行数);
-
-
-
代码实现:
-
提取工具类:
-
工具类:
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* JDBC工具类
*/
public class JdbcUtils {
private static String driver=null;
private static String url=null;
private static String username=null;
private static String password=null;
static {
try {
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
driver=properties.getProperty("driver");
url=properties.getProperty("url");
username=properties.getProperty("username");
password=properties.getProperty("password");
//1,驱动只用加载一次,
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException{
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
}
//释放连接
public static void release(Connection conn, Statement state, ResultSet res) {
if(res !=null){
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(state !=null){
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn !=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
-
-