在安卓应用程序中使用外部MySQL数据库可以通过以下步骤实现:
implementation 'mysql:mysql-connector-java:8.0.26'
然后,点击Sync Now以同步项目。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnection {
private static final String URL = "jdbc:mysql://your_mysql_host:your_mysql_port/your_database_name";
private static final String USERNAME = "your_mysql_username";
private static final String PASSWORD = "your_mysql_password";
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
}
请将"your_mysql_host"替换为MySQL主机地址,"your_mysql_port"替换为MySQL端口号,"your_database_name"替换为要连接的数据库名称,"your_mysql_username"和"your_mysql_password"替换为MySQL的用户名和密码。
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);
try {
connection = MySQLConnection.getConnection();
Statement statement = connection.createStatement();
String query = "SELECT * FROM your_table_name";
ResultSet resultSet = statement.executeQuery(query);
while (resultSet.next()) {
// 处理查询结果
String column1 = resultSet.getString("column1");
String column2 = resultSet.getString("column2");
// ...
}
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"替换为要查询的表名。在上述代码中,首先通过MySQLConnection.getConnection()方法获取数据库连接,然后创建Statement对象执行查询语句,并通过ResultSet对象获取查询结果。
需要注意的是,在使用外部MySQL数据库时,需要确保网络连接可用,并且MySQL数据库的主机地址、端口号、用户名和密码正确无误。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云