java怎么连接数据库
在Java中连接数据库通常需要以下步骤:
- 加载数据库驱动程序
- 建立数据库连接
- 编写SQL语句
- 执行SQL语句
- 处理查询结果
- 关闭连接
下面是一个简单的示例代码:
import java.sql.*;
public class ConnectDB {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载MySQL驱动程序
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语句
String sql = "SELECT * FROM customers";
// 执行SQL语句
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
// 处理查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
System.out.println("id: " + id + ", name: " + name + ", email: " + email);
}
} catch (Exception 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();
}
}
}
}
在这个示例中,我们使用了MySQL数据库,加载了MySQL驱动程序,建立了数据库连接,执行了一个简单的查询,并打印出结果。最后我们关闭了连接。这个示例只是一个简单的示例,实际应用中需要更多的错误处理和安全措施。
原文地址: http://www.cveoy.top/t/topic/LIh 著作权归作者所有。请勿转载和采集!