1、获得(设置)连接sql的参数
mysql连接需要的参数有驱动driver、数据库链接url、用户user、登录密码password
这些数据可以直接放在java类中,但是一般为安全我们放在配置文件properties中,通过读取配置文件参数来获取
/**
* 四个基本的mysql配置信息
*/
private static String driver;
private static String url;
private static String userName;
private static String password;
//静态代码块来初始化sql信息
static {
//创建获取配置文件对象
Properties properties = new Properties();
//得到一个读取配置文件流对象
InputStream in = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
try {
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
//读取文件获得数据
userName = properties.getProperty("userName");
password = properties.getProperty("password");
url = properties.getProperty("url");
driver = properties.getProperty(driver);
try {
//加载驱动类
Class.forName("driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
2、加载驱动
try {
//加载驱动类
Class.forName("driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
3、Connection对象连接mysql
连接mysql需要使用Connection对象来实现,其中Connect对象需要DriverManager对象来获得
private static Connection con;
public static Connection getConnection(){
//数据库连接
try{
con = DriverManager.getConnection("url","userName","password");
}catch (Exception e){
e.printStackTrace();
}
return con;
}
4、获得一个PrepareStatement对象来操作数据库
//sql例子
String sql = "select * from user where user name like ?";//模糊查询
//其中?为一个占位符,最后需要对其赋值
PrepareStatement pstm = connection.prepareStatement(sql);
//同时包含了一个预编译过程
pstm.setObject(1,"%林%");//1标识占位符的位置
//执行sql语句,使用ResultSet对象来存储我们查询的结果。
ResultSet rs = pstm.executeQuery();//只是执行查操作
5、资源释放:
sql执行完后,为了避免资源浪费,我们需要关闭Connection、PrepareSatement、ResultSet对象。**重要:**关闭的顺序要遵循“先开后关的原则”;也就是关闭顺序为ResultSet -》 PrepareSatement -》 Connection;代码实例为如下:
public static boolean closeResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
boolean flag = true;
if (resultSet != null) {
try {
resultSet.close();
//GC回收
resultSet = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
//GC回收
preparedStatement = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if (connection != null) {
try {
connection.close();
//GC回收
connection = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
return flag;
}