Android 客戶端 不能直接連接 MySQL(安全性、連接池、網絡穿透等問題)。標準架構為:
Android App --HTTP/HTTPS--> Tomcat (Spring Boot / Servlet) --JDBC/Connection Pool--> MySQL
JAVA_HOME、PATH。conf/server.xml:address="0.0.0.0" 允許外網訪問bin/startup.sh,瀏覽器訪問 https://server-ip:8080。-- 創建業務用戶
CREATE USER 'app_user'@'%' IDENTIFIED BY 'strong_password';
GRANT ALL PRIVILEGES ON your_db.* TO 'app_user'@'%';
FLUSH PRIVILEGES;
-- 確保 my.cnf 綁定 0.0.0.0
bind-address = 0.0.0.0
-- 重啟 MySQL 生效
<!-- context.xml 或 Spring 配置 -->
<Resource name="jdbc/MyDB"
auth="Container"
type="javax.sql.DataSource"
maxTotal="20"
maxIdle="10"
maxWaitMillis="-1"
username="app_user"
password="strong_password"
driverClassName="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/your_db?useSSL=false&serverTimezone=UTC&characterEncoding=utf8"
/>
使用 Spring Boot(推薦)或原生 Servlet + JSON 庫(Jackson/Gson)實現 CRUD 接口:
@RestController
@RequestMapping("/api/appointments")
public class AppointmentController {
@Autowired AppointmentService service;
@GetMapping("/list")
public List<Appointment> list(@RequestParam String userId) {
return service.findByUser(userId);
}
@PostMapping("/book")
public Result book(@RequestBody AppointmentDTO dto) {
return service.createAppointment(dto);
}
}
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
// Retrofit 定義
public interface ApiService {
@GET("api/appointments/list")
Call<List<Appointment>> getAppointments(@Query("userId") String userId);
@POST("api/appointments/book")
Call<Result> bookAppointment(@Body AppointmentDTO dto);
}
// 調用
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://your-server-ip:8080/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService api = retrofit.create(ApiService.class);
api.getAppointments("user123").enqueue(new Callback<List<Appointment>>() {
@Override public void onResponse(Call<List<Appointment>> call, Response<List<Appointment>> response) {
// 更新 UI
}
@Override public void onFailure(Call<List<Appointment>> call, Throwable t) {
// 錯誤處理
}
});
maxTotal、maxIdle,監控泄漏。Android 連接 Tomcat + MySQL 的核心是三層架構:客戶端通過 HTTP 調用 REST API,服務端業務邏輯層操作數據庫。切勿嘗試客戶端直連數據庫。掌握 Tomcat 部署、MySQL 遠程授權、連接池配置、REST API 開發、Retrofit 調用這五大核心環節,即可構建穩健的移動應用後端體系。