jdbc.properties文件
url=jdbc:mysql://localhost:3306/db1
user=root
password=123456
driver:com.mysql.jdbc.Driver
DBUtils工具类
package Demo;
import java.util.Properties;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtils {
private static String user;
private static String password;
private static String url;
private static String driver;
static {
// 静态代码块只需要加载一次,读取资源文件
try {
// 创建properties集合类
Properties pro=new Properties();
// 加载文件
pro.load(new FileReader("resource/jdbc.properties"));
// 获取数据,赋值
url=pro.getProperty("url");
user=pro.getProperty("user");
password=pro.getProperty("password");
driver=pro.getProperty("driver");
Class.forName(driver);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 获取连接对象
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
// 释放资源
public static void close(Statement st,Connection conn) {
close(null, st, conn);
}
public static void close(ResultSet rs,Statement st,Connection conn) {
if(null!=rs) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null!=st) {
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null!=conn) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
测试
package Demo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Test {
public static void main(String[] args) {
Connection conn=null;
//使用PreparedStatement可以避免SQL注入
PreparedStatement ps=null;
try {
//获取数据库连接对象
conn=DBUtils.getConnection();
//sql语句
String sql="delete from student where id= ?";
//创建执行sql对象
ps=conn.prepareStatement(sql);
//为占位符?赋值
ps.setInt(1, 13);
//执行sql
int count=ps.executeUpdate();
System.out.println(count);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DBUtils.close(ps, conn);
}
}
}