pom. xml 文件中引入依赖<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.3</version>
<scope>test</scope>
</dependency>
</dependencies>public class JDBCTest {
@Test
public void test() throws ClassNotFoundException, SQLException {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//连接数据库
String web01 = "jdbc:mysql://localhost:3306/web01";
String root = "root";
String password = "sqlCFPL@1210@HYS";
Connection connection = DriverManager.getConnection(web01, root, password);
//获取SQL语句执行对象
Statement statement = connection.createStatement();
//执行SQL
int i = statement.executeUpdate("update user set age=25 where id=1");
System.out.println("SQL执行影响记录数为:"+i);
//释放资源
statement.close();
connection.close();
}
}@Test
public void test() throws ClassNotFoundException, SQLException, IOException {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//连接数据库
String url = "jdbc:mysql://localhost:3306/web01";
String user = "root";
String password = "sqlCFPL@1210@HYS";
//预编译SQL,速度快,安全度高
String sql = "SELECT id, username, password, name, age FROM user WHERE username = ? AND password = ?";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
// 设置查询参数
pstmt.setString(1, "daqiao");
pstmt.setString(2, "123456");
// 执行查询(封装查询返回的结果)
ResultSet rs = pstmt.executeQuery();
// 处理结果集
while (rs.next()) {
User userObj = new User(
rs.getInt("id"),
rs.getString("username"),
rs.getString("password"),
rs.getString("name"),
rs.getInt("age")
);
// 输出User对象到控制台
System.out.println(userObj);
}
} catch (SQLException e) {
e.printStackTrace();
}
}JDBC 程序执行 SQL 语句
int rowsAffected = statement. ExecuteUpdate ();ResultSet(结果集对象):封装了DQL查询语句查询的结果。
resuletSet.next():将光标从当前位置向前移动一行,并判断当前行是否为有效行,返回值为boolean。
resuletSet.getXxx(…):获取数据,可以根据列的编号获取,也可以根据列名获取(推荐)
在介绍预编译 SQL 之前,先介绍静态 SQL。
//获取SQL语句执行对象
Statement statement = connection.createStatement();
//执行SQL
int i = statement.executeUpdate("update user set age=25 where id=1");
System.out.println("SQL执行影响记录数为:"+i); ?)来代表参数,在运行时再传入具体的值。//预编译SQL,速度快,安全度高
String sql = "SELECT id, username, password, name, age FROM user WHERE username = ? AND password = ?";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
// 设置查询参数
pstmt.setString(1, "daqiao");
pstmt.setString(2, "123456");
// 执行查询(封装查询返回的结果)
ResultSet rs = pstmt.executeQuery(); 以下是相较于静态 SQL 对比
到这里,JDBC的入门结束,在此基础上,可以了解更多框架 (MyBatis, MyBatisPlus,Hibernate,SpringDataJPA 等),进行下一步学习。