【Android 远程数据库操作】
创始人
2024-10-17 13:41:54
0

按正常情况下,前端不应该直接进行远程数据库操作,这不是一个明智的方式,应该是后端提供对应接口来处理,奈何公司各方面原因需要前端这样做。

对此,我对远程数据库操作做了总结,便于自己复盘,同时,也分享给有需要的朋友们。

0、下载jdbc库

下载mysql官网:https://dev.mysql.com/downloads/connector/j/,按图片步骤下载所需jdbc的库
在这里插入图片描述在这里插入图片描述

1、添加jdbc驱动依赖包

在Android studio的项目工程app-bulid.grade添加依赖:implementation files(‘libs/mysql-connector-java-5.1.48.jar’)或implementation 'mysql:mysql-connector-java:5.1.48’这两种方式
在这里插入图片描述

2、数据库连接操作

			private String DB_URL = "jdbc:mysql://127.0.0.1:3306/远程数据库名";//换成远程地址    		    private String USER = "admin";//账号    		    private String PASS = "123456";	//密码     		 			// Step 1: 加载 JDBC driver             Class.forName("com.mysql.jdbc.Driver");//mysql高版本这里:com.mysql.cj.jdbc.Driver              // Step 2: 打开连接             Connection connection = DriverManager.getConnection(DB_URL, USER, PASS); 

3、执行数据库语句操作,进行相关业务处理

			String sql = "select name, age, sex from User";// sql语句 			Statement statement = connection.createStatement();             ResultSet rs = statement.executeQuery(sql);             while (rs.next() && !isStopped) { 				// todo 相应业务处理 			} 

4、数据库关闭

			// 操作完毕,数据库关闭 			rs.close();             statement.close();             connection.close(); 

5、完整代码

远程数据库操作工具类DatabaseAccessUtil,由于是耗时动作,需要在线程处理。

public class DatabaseAccessUtil {      private static final String TAG = "F100 DatabaseAccess";      private String DB_URL = "jdbc:mysql://127.0.0.1:3306/数据库名";     private String USER = "admin";     private String PASS = "123456";      private static DatabaseAccessUtil instance;     private ExecutorService executorService;     private volatile boolean isStopped = false;     private Future currentTask = null; // 用于保存当前的任务      private ProgressDialogUtil progressDialogUtil;     private Handler mainHandler;      private DatabaseAccessUtil() {         this.executorService = Executors.newSingleThreadExecutor();         mainHandler = new Handler(Looper.getMainLooper());     }      public static synchronized DatabaseAccessUtil getInstance() {         if (instance == null) {             instance = new DatabaseAccessUtil();         }         return instance;     }      public void start(Context context) {         stop();         isStopped = false;         if (executorService == null || executorService.isShutdown()) {             executorService = Executors.newSingleThreadExecutor();         }          if (!isStopped && !executorService.isShutdown()) {             currentTask = executorService.submit(() -> downloadData(context));         }     }      public void stop() {         isStopped = true;         if (currentTask != null) {             currentTask.cancel(true); // 尝试取消当前任务             currentTask = null;             executorService.shutdownNow(); // 停止执行器服务         }     }      private void showProgressDialog(Context context) {         mainHandler.post(() -> {             if (progressDialogUtil == null) {                 progressDialogUtil = new ProgressDialogUtil(context);                 progressDialogUtil.setOnCancelListener(() -> {                     stop();                 });             }             progressDialogUtil.showProgressDialog();         });     }      // 查询表的总数量     private int getTotalCountFromDB(Connection connection) throws SQLException {         String sql = "select count(*) from User";         Statement statement = connection.createStatement();         ResultSet rs = statement.executeQuery(sql);         rs.next();         int totalCount = rs.getInt(1);         rs.close();         statement.close();         return totalCount;     }      // 下载数据(相应业务处理)     private void downloadData(Context context) {         if (isStopped) return;          try {             String sql = "select name, age, sex from User";             // Step 1: Register JDBC driver             Class.forName("com.mysql.jdbc.Driver");//mysql高版本这里:com.mysql.cj.jdbc.Driver              // Step 2: Open a connection             Connection connection = DriverManager.getConnection(DB_URL, USER, PASS);              // Step 3: Execute a query             int totalCount = getTotalCountFromDB(connection);             if (totalCount == 0) {                 connection.close();                 EventBus.getDefault().post(new CommonEvent(EventCode.FLAG_NO_DATA));                 return;             }              // 显示进度条             // todo showProgressDialog(context);              // 执行sql 业务逻辑             Statement statement = connection.createStatement();             ResultSet rs = statement.executeQuery(sql);              int count = 0;             while (rs.next() && !isStopped) {                 // 进度条更新                 count++;                 int progress = (count * 100) / totalCount;                 updateProgress(progress);                  // Retrieve by column name                 String name = rs.getString("name");                 int age = rs.getInt("age");                 String sex = rs.getString("sex");                  // todo 业务逻辑处理              }              // 关闭             rs.close();             statement.close();             connection.close();              // 主线程回调, 这里我使用订阅             EventBus.getDefault().post(new CommonEvent(EventCode.FLAG_SUCCESS));         } catch (Exception e) {             // 主线程回调             EventBus.getDefault().post(new CommonEvent(EventCode.FLAG_FAIL));         } finally {             // 进度条关闭             mainHandler.post(() -> {                 if (progressDialogUtil != null) progressDialogUtil.dismissProgressDialog();             });         }     }      // 进度条更新     private void updateProgress(int progress) {         mainHandler.post(() -> {             if (progressDialogUtil != null) {                 progressDialogUtil.updateProgress(progress);             }         });     }  } 

进度条ProgressDialogUtil,布局:一个进度条+进度条进度+取消按钮,【取消】按钮是1分钟后可点击。代码如下:

public class ProgressDialogUtil {      private final long DELAY_TIME = 1 * 60 * 1000;//2分钟  2 * 60 * 1000      private Dialog progressDialog;     private ProgressBar progressBar;     private TextView tvProgress;     private Button btnCancel;     private Handler handler;     private boolean cancelEnabled = false;      public ProgressDialogUtil(Context context) {         progressDialog = new Dialog(context, R.style.CustomProgressDialog);         progressDialog.setContentView(R.layout.dialog_progress);         progressDialog.setCancelable(false);          progressBar = progressDialog.findViewById(R.id.progressBar);         tvProgress = progressDialog.findViewById(R.id.tvProgress);         btnCancel = progressDialog.findViewById(R.id.btnCancel);         btnCancel.setEnabled(false);          handler = new Handler();     }      public void showProgressDialog() {         Window window = progressDialog.getWindow();         if (window != null) {             WindowManager.LayoutParams params = window.getAttributes();             params.width = 650;             window.setAttributes(params);         }         progressDialog.show();         // 2分钟后显示         handler.postDelayed(new Runnable() {             @Override             public void run() {                 if (progressDialog.isShowing()) {                     cancelEnabled = true;                     btnCancel.setEnabled(true);                 }             }         }, DELAY_TIME);     }      public void dismissProgressDialog() {         if (progressDialog != null && progressDialog.isShowing()) progressDialog.dismiss();     }      public void updateProgress(int progress) { //        while (progress <= 97) {             progressBar.setProgress(progress);             tvProgress.setText(progress + "%"); //        }     }      public void setOnCancelListener(Runnable cancelAction) {         btnCancel.setOnClickListener(v->{             if (cancelEnabled) {                 cancelAction.run();                 dismissProgressDialog();             }         });     } } 

这篇文章提供全部代码和操作思路,拿来就可以使用。

如果觉得还不错,给个一键三连呗~~~

相关内容

热门资讯

咪咕安卓系统固件,深度解析与全... 你有没有发现,最近你的咪咕安卓手机更新了固件?别小看了这个小小的升级,它可是给我们的手机带来了不少惊...
安卓系统预览版,前沿功能与未来... 你知道吗?最近安卓系统又出新花样了!这不,安卓系统预览版已经悄悄上线,让咱们这些数码爱好者兴奋不已。...
安卓系统使用内核版本,揭秘安卓... 你有没有发现,每次打开你的安卓手机,它都在默默地进行着各种复杂的操作?这背后,可是有一个强大的内核在...
安卓虚拟系统怎么开机,开机流程... 你有没有想过,你的安卓手机里竟然可以藏着一个虚拟的小世界?没错,就是安卓虚拟系统!这个神奇的功能,让...
基于安卓内核的系统,功能与创新... 你知道吗?在科技飞速发展的今天,手机操作系统可是咱们日常生活中不可或缺的好伙伴。而说到手机系统,不得...
安卓系统怎么打开php,并且你... 你有没有想过,手机里装了安卓系统,怎么才能轻松打开PHP文件呢?别急,今天就来给你详细讲解让你轻松搞...
安卓系统蓝牙文件在哪,安卓系统... 你有没有遇到过这种情况:手机里存了好多好用的文件,突然想分享给朋友,却发现不知道安卓系统的蓝牙文件在...
电脑安卓系统安装app,畅享智... 你有没有想过,你的安卓手机里那些琳琅满目的APP是怎么来的呢?今天,就让我带你一探究竟,看看电脑上安...
智能安卓点歌系统固件,打造个性... 你有没有想过,家里的智能安卓点歌系统固件竟然也能玩出花来?没错,就是那个我们平时可能不太注意的小玩意...
门口门禁安卓系统 开源,基于开... 你有没有想过,家里的门口门禁系统其实也可以变得酷炫又智能呢?想象当你回家时,门禁系统自动识别你的手机...
vidda系统和安卓系统哪个好... 最近手机圈里可是热闹非凡呢!不少朋友都在问我:“Vida系统和安卓系统哪个好?”这个问题可真是让人头...
手机安卓系统和ios系统下载,... 你有没有发现,现在手机的世界里,安卓系统和iOS系统就像是一对双胞胎,各有各的特色,让人挑花了眼。今...
手机安卓系统无法恢复,揭秘手机... 手机里的安卓系统突然崩溃了,是不是感觉整个人都不好了?别急,让我来给你详细说说这个头疼的问题,说不定...
ios系统改不了安卓,探索解决... 你有没有想过,为什么你的iPhone手机上的iOS系统就不能换成安卓系统呢?是不是觉得这个限制有点让...
安卓系统怎么双开应用,安卓系统... 如何在安卓系统上双开应用:一步步指南在数字化时代,手机已经成为我们生活中不可或缺的一部分。无论是社交...
安卓机的散热系统,揭秘高效散热... 你有没有发现,夏天用安卓手机的时候,手机总是热得像个小火炉?别急,今天就来给你揭秘安卓机的散热系统,...
怎么清除安卓系统缓存,提升手机... 手机用久了是不是感觉越来越卡?别急,今天就来教你怎么清除安卓系统的缓存,让你的手机焕然一新!一、缓存...
安卓系统照片自动清理,释放存储... 手机里的照片是不是越来越多,感觉内存都要不够用了?别急,今天就来给你支个招——安卓系统照片自动清理!...
安卓系统咸鱼怎么登录,畅享二手... 你有没有发现,有时候手机里装了太多APP,登录起来简直像是在玩捉迷藏呢?今天,就让我来带你一探究竟,...
简单的安卓开发系统,系统架构与... 你有没有想过,自己动手打造一个安卓应用?别看那些专业的开发者们好像离我们很远,其实,简单的安卓开发系...