idea中怎么连接数据库
时间: 2023-05-24 13:00:59 浏览: 45
您可以使用JDBC连接数据库。首先在pom.xml中添加相应的依赖,然后通过以下代码连接数据库:
```java
public static void main(String[] args) {
// 数据库连接信息
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "password";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 注册 JDBC 驱动器、打开连接
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
// 执行查询
stmt = conn.createStatement();
String sql = "SELECT id, name, age FROM users";
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 + "\t" + name + "\t" + age);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (rs != null) rs.close();
} catch (SQLException se) {
se.printStackTrace();
}
try {
if (stmt != null) stmt.close();
} catch (SQLException se) {
se.printStackTrace();
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
```
其中url为数据库的连接地址,username为用户名,password为密码。在try-catch-finally语句块中执行SQL查询。最后记得关闭资源。