package com.jdbcUtils;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
//连接参数
private static String user;
private static String password;
private static String url;
private static String driver;
//用static代码块去初始化
static{
try {
Properties properties=new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
user=properties.getProperty("user");
password=properties.getProperty("password");
url=properties.getProperty("url");
driver=properties.getProperty("driver");
} catch (IOException e) {
//实际开发中将编译异常转为运行异常,调用者捕获或者默认处理
throw new RuntimeException(e);
}
}
//连接数据库 返回connection
public static Connection getConnection(){
try {
Class.forName(driver);
return DriverManager.getConnection(url,user,password);
} catch (Exception e) {
//实际开发中将编译异常转为运行异常,调用者捕获或者默认处理
throw new RuntimeException(e);
}
}
//关闭资源 1.ResultSet PrepareStatement Connection
//传如null不关闭
public static void close(ResultSet rs, Statement statement,Connection connection){
try {
if (rs!=null) {
rs.close();
}
if (statement!=null) {
statement.close();
}
if (connection!=null) {
connection.close();
}
} catch (SQLException e) {
//实际开发中将编译异常转为运行异常,调用者捕获或者默认处理
throw new RuntimeException(e);
}
}
}
JdbcConnect 测试代码
package com.company;
import com.jdbcUtils.JdbcUtils;
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;
public class JdbcConnect {
@Test
public void connection() throws IOException {
Connection connection=null;
PreparedStatement ps=null;
ResultSet rs=null;
/*
try {
//获取连接
connection=JdbcUtils.getConnection();
//创建sql语句
String sql="update user set name=? where name=?";
//创建执行者对象
ps=connection.prepareStatement(sql);
//参数赋值
ps.setString(1,"大菜鸡");
ps.setString(2,"小菜鸡");
//执行sql
int row=ps.executeUpdate();//返回影响的行数
System.out.println(row);//测试
JdbcUtils.close(null,ps,connection);
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭连接
JdbcUtils.close(rs,ps,connection);
}
*/
try {
//获取连结
connection=JdbcUtils.getConnection();
//创建sql语句
String sql="select *from user where name=?";
//创建执行者对象
ps=connection.prepareStatement(sql);
//参数赋值
ps.setString(1,"大菜鸡");
//创建结果集对象
rs=ps.executeQuery();
//循环遍历输出结果
while(rs.next()){//rs往后走一行有数据进入循环体
String name=rs.getString("name");
String pwd=rs.getString("pwd");
System.out.println("name:"+name+"pwd:"+pwd);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭连接
JdbcUtils.close(rs,ps,connection);
}
}
}