编写一个jdbc程序,要求如下1.驱动程序:COM.mysql.jdbc 2.url:jdbc:mysql://
时间: 2023-07-15 11:14:58 浏览: 98
我可以提供一个简单的 JDBC 程序范例,您可以根据自己的需求进行修改。
首先,您需要下载 MySQL 的 JDBC 驱动程序,并将其添加到您的项目中。
在程序中,您需要指定 MySQL 数据库的 url、用户名和密码。
以下是一个简单的 JDBC 程序:
```
import java.sql.*;
public class JdbcExample {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立连接
String url = "jdbc:mysql://localhost:3306/mydb"; // 这里的 mydb 是您的数据库名
String user = "root"; // 这里的 root 是您的用户名
String password = "password"; // 这里的 password 是您的密码
conn = DriverManager.getConnection(url, user, password);
// 创建 Statement 对象
stmt = conn.createStatement();
// 执行 SQL 语句
String sql = "SELECT * FROM mytable"; // 这里的 mytable 是您的表名
rs = stmt.executeQuery(sql);
// 处理结果集
while (rs.next()) {
int id = rs.getInt("id"); // 这里的 id 是您的表中的列名
String name = rs.getString("name"); // 这里的 name 是您的表中的列名
System.out.println("id: " + id + ", name: " + name);
}
} 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();
}
}
}
}
```
请注意,这里的 url、用户名和密码都需要根据您的实际情况进行修改。
阅读全文
相关推荐














