在Android中直接连接MySQL数据库并不是一个好主意,因为这样会暴露数据库的用户名和密码,可能导致安全问题。推荐的做法是使用Web服务(如RESTful API)作为中间层,让Android应用程序通过HTTP请求与Web服务进行通信,然后Web服务负责与MySQL数据库交互。
以下是使用Web服务连接MySQL数据库的简要步骤:
创建一个Web服务(例如,使用PHP、Node.js或Python编写的API)。在Web服务中,编写代码来处理与MySQL数据库的连接和查询。将Web服务部署到服务器上,以便Android应用程序可以访问它。在Android应用程序中,使用网络库(如Retrofit、Volley或OkHttp)发起HTTP请求,与Web服务进行通信。处理Web服务返回的数据,并在Android应用程序中显示。这里有一个简单的示例,展示了如何使用PHP和MySQL创建一个Web服务,并在Android应用程序中使用Volley库发起请求:
PHP Web服务(get_data.php):
<?php$servername = "localhost";$username = "your_username";$password = "your_password";$dbname = "your_database";// 创建连接$conn = new mysqli($servername, $username, $password, $dbname);// 检查连接if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}// 查询数据$sql = "SELECT id, name, email FROM users";$result = $conn->query($sql);$data = array();if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $data[] = $row; }} else { echo "0 results";}// 关闭连接$conn->close();// 将数据转换为JSON格式echo json_encode($data);?>Android应用程序(使用Volley库):
添加Volley依赖项到build.gradle文件:dependencies { implementation 'com.android.volley:volley:1.2.1'}在Android应用程序中发起请求:import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.TextView;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;public class MainActivity extends AppCompatActivity { private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); String url = "https://yourserver.com/get_data.php"; RequestQueue queue = Volley.newRequestQueue(this); StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONArray jsonArray = new JSONArray(response); for (int i = 0; i< jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String name = jsonObject.getString("name"); String email = jsonObject.getString("email"); textView.append(name + " - " + email + "\n"); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { textView.setText("Error: " + error.getMessage()); } }); queue.add(stringRequest); }}这个示例展示了如何在Android应用程序中使用Volley库从PHP Web服务获取数据,并将其显示在TextView中。请确保将URL替换为你自己的服务器地址。


