jdbc连接mysql数据库代码

网站编辑2023-05-16 11:16:28696

以下是使用 JDBC 连接 MySQL 数据库的示例代码:

```java

import java.sql.*;

public class MySQLJDBCExample {

public static void main(String[] args) {

String url = "jdbc:mysql://localhost:3306/mydatabase"; // 数据库 URL

String user = "root"; // 数据库用户名

String password = "password"; // 数据库密码

try {

// 加载 MySQL JDBC 驱动程序

Class.forName("com.mysql.jdbc.Driver");

// 建立数据库连接

Connection conn = DriverManager.getConnection(url, user, password);

// 创建 SQL 语句

String sql = "SELECT * FROM mytable";

// 创建 Statement 对象

Statement stmt = conn.createStatement();

// 执行 SQL 查询

ResultSet 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);

}

// 关闭连接

rs.close();

stmt.close();

conn.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

```

在上面的示例代码中,我们首先加载 MySQL JDBC 驱动程序,然后使用 `DriverManager.getConnection()` 方法建立数据库连接。接着,我们创建 SQL 语句并使用 `conn.createStatement()` 方法创建 Statement 对象。最后,我们使用 `stmt.executeQuery()` 方法执行 SQL 查询,并使用 `ResultSet` 对象处理查询结果。最后,我们关闭连接以释放资源。

最新推荐

右侧广告图1
右侧广告图2