JDBC连接MySQL数据库实现步骤
1,加载JDBC驱动(jar驱动包自己去下)
2,建立数据库连接(Connection接口)
3,准备SQL语句
4,预编译处理
5,执行并返回结果
6,处理结果集(选择适当的接口)
7,关闭数据连接(这里要注意顺序,要先关小门后关大门)
由于使用的是MySQL数据库,它的URL一般为,jdbc:mysql://主机地址:端口号/库名。
public void doFind(){
// 1. 加载mysql驱动
Class.forName(“com.mysql.jdbc.Driver”);
// 2. 创建数据库连接
Connection conn = DriverManager.getConnection(url,”root”,”123456”);
// 3. 准备SQL语句
String sql = “select * from tb_user”;
// 4. 预编译处理
PreparedStatement pstm = conn.preparedStatement(sql);
// 5. 执行并返回结果
ResultSet rs = pstm.executeQuery();
// 6. 处理结果
while(rs.next()){
syso();
}
// 7. 释放资源
rs.close();
pstm.close();
conn.close();
}
具体封装代码
创建一个DBUtil类
public class DBUtil {
// 解决维护性功能 properties
private static String driver ;
private static String url ;
private static String jdbcuser ;
private static String pwd ;
public Connection conn = null;
public PreparedStatement pstm = null;
public ResultSet rs = null;
public static Properties properties = new Properties();
// 获取db.properties资源 , static方法代表软件一打开就会自动加载资源文件
static {
try {
properties.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
driver = properties.getProperty("driver");
url = properties.getProperty("url");
jdbcuser = properties.getProperty("jdbcuser");
pwd = properties.getProperty("pwd");
} catch (IOException e) {
e.printStackTrace();
}
}
// 1. 实现数据库连接的获取
public Connection getConn(){
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, jdbcuser, pwd);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
// 2. 实现增删改的BaseDao封装
public int executeUpdate(String sql,Object[] params){ // Object[] 占位?不知道是什么数据类型,所有用了泛型处理
int num = 0;
try {
pstm = conn.prepareStatement(sql);
// 怎么处理占位符?
if(params!=null){
for(int i=0;i<params.length;i++){
pstm.setObject((i+1),params[i]);
}
}
num = pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return num;
}
// 3. 实现查询的BaseDao封装
public ResultSet executeQuery(String sql,Object[] params){
ResultSet rs = null;
try {
pstm = conn.prepareStatement(sql);
// 怎么处理占位符?
if(params!=null){
for(int i=0;i<params.length;i++){
pstm.setObject((i+1),params[i]);
}
}
rs = pstm.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
// 4. 实现数据库资源释放
public void closeResource(ResultSet rs, PreparedStatement pstm,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(pstm!=null){
try {
pstm.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}