使用 JDBC 连接数据库
时间: 2023-07-03 21:07:07 浏览: 56
JDBC(Java Database Connectivity)是Java语言访问数据库的标准API。使用JDBC连接数据库可以实现Java程序与各种关系型数据库(如MySQL、Oracle、SQL Server等)的交互操作。
下面是使用JDBC连接MySQL数据库的示例代码:
```java
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
try {
// 加载数据库驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
// 建立数据库连接
Connection conn = DriverManager.getConnection(url, user, password);
// 创建Statement对象
Statement stmt = conn.createStatement();
// 执行查询语句
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
// 处理查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("id=" + id + ", name=" + name + ", age=" + age);
}
// 关闭结果集、Statement和连接
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们首先通过`Class.forName`方法加载了MySQL数据库驱动程序,然后使用`DriverManager.getConnection`方法建立了与MySQL数据库的连接。接着创建了一个`Statement`对象,使用它执行了一条查询语句,并通过`ResultSet`对象获取查询结果。最后,我们关闭了结果集、Statement和连接。
需要注意的是,在实际开发中,为了避免SQL注入等安全问题,我们通常使用PreparedStatement对象来执行SQL语句。另外,如果涉及到事务处理,需要使用Connection对象的事务管理方法来控制事务的提交和回滚。