用Android studio写连接MySQL的Java类
时间: 2024-05-14 22:14:20 浏览: 121
android连接MySQL数据库
首先需要在Android Studio中添加MySQL JDBC驱动库,可以在build.gradle文件中添加以下依赖:
```
dependencies {
// ...
implementation 'mysql:mysql-connector-java:8.0.23'
}
```
然后可以创建一个名为MySQLConnector的Java类,用于连接MySQL数据库和执行查询操作。代码如下:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQLConnector {
private Connection connection;
private Statement statement;
private ResultSet resultSet;
// 连接MySQL数据库
public void connect() throws SQLException {
String url = "jdbc:mysql://localhost:3306/db_name";
String user = "username";
String password = "password";
connection = DriverManager.getConnection(url, user, password);
}
// 执行查询操作
public ResultSet executeQuery(String sql) throws SQLException {
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
return resultSet;
}
// 关闭连接
public void close() throws SQLException {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
}
```
其中connect方法用于连接MySQL数据库,executeQuery方法用于执行查询操作,close方法用于关闭连接。
使用示例:
```java
MySQLConnector connector = new MySQLConnector();
try {
connector.connect();
ResultSet resultSet = connector.executeQuery("SELECT * FROM table_name");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// ...
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connector.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
```
阅读全文