JDBC在系统中的位置
数据库连接需要导入的包
- java.sql
- 数据库驱动包:mysql-connector-java-8.0.28.jar
JDBC连接数据库流程
public class JdbcTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取用户信息和url用于连接数据库
/*
* jdbctest:要连接的数据库
* useUnicode=true&characterEncodig=utf8:编码设置
*useSSL=false:SSL安全验证,低版本MySQL默认false;高版本必须设置,通常使用useSSL=false
*?:连接参数
* */
String url = "jdbc:mysql//localhost:3306/jdbctest?useUnicode=true&characterEncodig=utf8&useSSL=false";
String username = "root";
String password = "123456";
//3.获取数据库对象 Connection代表数据库
Connection connection = DriverManager.getConnection(url,username,password);
//4.获取执行SQL的对象 Statement代表执行SQL的对象
Statement statement = connection.createStatement();
//5.执行SQL语句,返回结果集
String sql = "select * from users";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("name="+resultSet.getObject("name"));
System.out.println("password="+resultSet.getObject("pwd"));
System.out.println("email="+resultSet.getObject("email"));
}
//6.释放连接
resultSet.close();
statement.close();
connection.close();
}
}
JdbcUtils工具类
用文件存储信息,以后数据库连接信息更改后直接改文件就行
数据库连接封装
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 resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("uesrname");
password = properties.getProperty("password");
//驱动只需加载一次
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
//释放连接
public static void release(Connection conn, Statement st, ResultSet rs){
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
插入测试
public class TsetInsert {
public static void main(String[] args) {
Connection connection= null;
Statement statement = null;
ResultSet resultSet = null;
try {
//获取数据库连接对象
connection = JdbcUtils.getConnection();
//创建数据库执行对象
statement = connection.createStatement();
String sql = "insert into users(id, `name`) values(4, ``abc)";
int i = statement.executeUpdate(sql);
//i是返回受影响的行数
if (i>0)
System.out.println("插入成功");
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.release(connection,statement,null);
}
}
}
在此基础上可以把main方法改成需要传参为sql语句的方法,将crud操作进一步封装
步骤总结:
- 加载驱动
- 连接数据库
- 获取数据库对象
- 获取执行SQL的对象
- 执行SQL语句,返回结果集
- 释放连接