帮我写一段Java数据库
时间: 2023-08-17 20:19:53 浏览: 45
好的,以下是一个简单的Java数据库连接示例:
```java
import java.sql.*;
public class MySQLDatabase {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载MySQL JDBC驱动
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
// 执行SQL语句
stmt = conn.createStatement();
String sql = "SELECT * FROM user";
rs = stmt.executeQuery(sql);
// 处理查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("id: " + id + ", name: " + name);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
这个示例程序使用了JDBC驱动连接MySQL数据库,查询了一个名为"user"的表,并打印了结果。在实际开发中,还需要注意连接池、SQL注入等安全问题。