在Android中直接連接MySQL數(shù)據(jù)庫(kù)并不是一個(gè)好主意,因?yàn)檫@樣會(huì)暴露數(shù)據(jù)庫(kù)的用戶名和密碼,可能導(dǎo)致安全問(wèn)題。推薦的做法是使用Web服務(wù)(如RESTful API)作為中間層,讓Android應(yīng)用程序通過(guò)HTTP請(qǐng)求與Web服務(wù)進(jìn)行通信,然后Web服務(wù)負(fù)責(zé)與MySQL數(shù)據(jù)庫(kù)交互。
以下是使用Web服務(wù)連接MySQL數(shù)據(jù)庫(kù)的簡(jiǎn)要步驟:
這里有一個(gè)簡(jiǎn)單的示例,展示了如何使用PHP和MySQL創(chuàng)建一個(gè)Web服務(wù),并在Android應(yīng)用程序中使用Volley庫(kù)發(fā)起請(qǐng)求:
PHP Web服務(wù)(get_data.php):
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 創(chuàng)建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 查詢(xún)數(shù)據(jù)
$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";
}
// 關(guān)閉連接
$conn->close();
// 將數(shù)據(jù)轉(zhuǎn)換為JSON格式
echo json_encode($data);
?>
Android應(yīng)用程序(使用Volley庫(kù)):
build.gradle
文件:dependencies {
implementation 'com.android.volley:volley:1.2.1'
}
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);
}
}
這個(gè)示例展示了如何在Android應(yīng)用程序中使用Volley庫(kù)從PHP Web服務(wù)獲取數(shù)據(jù),并將其顯示在TextView
中。請(qǐng)確保將URL替換為你自己的服務(wù)器地址。