- 创建一个普通的Java项目
- 导入数据库驱动(导入jar包)
- 在项目文件夹下新建一个lib文件夹,再把下载好的jar包粘贴到该文件夹下,并右键选择Add As Library。(学习了Maven后直接用maven导入包就行)
- 编写测试代码
import java.sql.*;
public class JDBCFirstDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1、加载数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2、把用户信息和url存入到变量中
String url = "jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&useSSl=true";
String user = "XXXX";
String pwd = "XXXXXXX"; //填写自己数据库连接的用户和密码
//3、建立连接,连接数据库,数据库对象connection代表数据库
Connection connection = DriverManager.getConnection(url, user, pwd);
//4、执行SQL的对象statement
Statement statement = connection.createStatement();
//5、把SQL语句写入变量,并用statement对象去执行SQL,把可能产生的结果写入resultSet对象
String sql = "SELECT * FROM app_user WHERE id = 328472";
ResultSet resultSet = statement.executeQuery(sql); //结果集,封装了我们查询的全部结果
while (resultSet.next()) {
System.out.print("id:" + resultSet.getInt("id") + " ");
System.out.print("name:" + resultSet.getString("name") + " ");
System.out.print("email:" + resultSet.getString("email") + " ");
System.out.print("phone:" + resultSet.getString("phone") + " ");
System.out.print("gender:" + (resultSet.getInt("gender") == 0 ? "男" : "女") + " ");
System.out.print("password:" + resultSet.getString("password") + " ");
System.out.print("age:" + resultSet.getInt("age") + " ");
System.out.println("create_time:" + resultSet.getDate("create_time") + " ");
System.out.println("update_time:" + resultSet.getDate("update_time") + " ");
System.out.println("======================================");
}
//6.关闭创建的连接
resultSet.close();
statement.close();
connection.close();
}
}
步骤总结:
- 加载数据库驱动,选择使用的数据库,不同的数据库有不同的驱动
- 连接数据库DriverManager
- 获得执行数据库的对象Statement
- 执行SQL
- 返回获得的结果集ResultSet(查询才会有结果集)
- 释放连接