要在Android应用程序中连接到MySQL数据库,可以使用以下步骤:
implementation 'mysql:mysql-connector-java:8.0.23'
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String URL = "jdbc:mysql://your_mysql_server_ip:port/your_database_name";
private static final String USER = "your_mysql_username";
private static final String PASSWORD = "your_mysql_password";
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return connection;
}
}
请确保将your_mysql_server_ip
,port
,your_database_name
,your_mysql_username
和your_mysql_password
替换为实际的MySQL服务器IP地址,端口号,数据库名称,用户名和密码。
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
private Connection connection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取数据库连接
connection = DatabaseConnection.getConnection();
// 执行查询
executeQuery("SELECT * FROM your_table_name");
}
private void executeQuery(String query) {
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
// 处理结果集
while (resultSet.next()) {
// 从结果集中获取数据
String data = resultSet.getString("column_name");
// 打印数据
Log.d("MySQL Data", data);
}
// 关闭结果集和语句
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// 关闭数据库连接
try {
if (connection != null && !connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
请确保将your_table_name
替换为实际的表名,column_name
替换为实际的列名。
这是一个基础示例,用于在Android应用程序中连接到MySQL数据库并执行查询。你可以根据自己的需求进行修改和扩展。
下一篇:Android连接服务场景