帮我写一个java连接mysql的客户端,原生实现
时间: 2024-03-08 10:50:25 浏览: 20
好的,以下是一个简单的Java连接MySQL的客户端示例代码:
```java
import java.sql.*;
public class MySQLClient {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载MySQL的驱动类
Class.forName("com.mysql.jdbc.Driver");
// 获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname", "username", "password");
// 创建Statement对象
stmt = conn.createStatement();
// 执行SQL语句
rs = stmt.executeQuery("SELECT * FROM table_name");
// 处理结果集
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
这个示例代码中,我们使用了JDBC连接MySQL数据库。首先,我们加载了MySQL的驱动类,然后获取连接,创建Statement对象,执行SQL语句,处理结果集,最后关闭连接。注意需要替换示例代码中的数据库名、用户名和密码。