java连接数据库的基本步骤有哪些,可以给出一个代码示例吗
时间: 2024-04-30 13:22:47 浏览: 10
Java连接数据库的基本步骤如下:
1. 导入数据库驱动包
2. 加载驱动类
3. 建立数据库连接
4. 创建Statement对象
5. 执行SQL语句
6. 处理查询结果
7. 关闭数据库连接
代码示例:
```
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 建立数据库连接
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url, username, password);
// 创建Statement对象
stmt = conn.createStatement();
// 执行SQL语句
String sql = "SELECT * FROM user";
rs = stmt.executeQuery(sql);
// 处理查询结果
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);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```