安卓怎么新开线程连接MySQL,针对Android不同的线程数据库访问

I have a Service that downloads data from the Internet in AsyncTasks. It parses the data and store it in a db. The Service runs continuously.

There is a change that a Activity attempts to read from the db while the Service is writing to it.

I have a database helper with several methods for writing and reading. Could this cause problems? Potentially trying to open the db from two different threads?

解决方案

there has been talked and written many books about concurrency problems in db .

But using stackoverflow like a wikipedia i have found some interesting thing:

Sqlite on android lets you access the database from multiple procs for

reads, but if you're currently writing from one process, reads and

writes from other procs will throw an exception because the first

write has a lock on the db.

Then the database is well protected from others threads . The bad news is that you must manage those exceptions , and can be a dirty work if you have a big database (meaning with big many tables with much data exchange)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Studio 中启动 MySQL 数据库需要使用一个 Java 库来连接 MySQL 数据库。Java 库通常提供多种连接方式,其中最常用的是 JDBC(Java 数据库连接)。 下面是使用线程启动 MySQL 数据库的基本步骤: 1. 在项目的 build.gradle 文件中添加 MySQL 连接库的依赖项: ```groovy dependencies { implementation 'mysql:mysql-connector-java:8.0.16' } ``` 2. 在代码中启动数据库连接线程: ```java public class DatabaseConnector extends Thread { private static final String TAG = "DatabaseConnector"; private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase"; private static final String DB_USER = "user"; private static final String DB_PASSWORD = "password"; @Override public void run() { Connection conn = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); Log.d(TAG, "Connected to database"); } catch (ClassNotFoundException e) { Log.e(TAG, "Failed to load database driver", e); } catch (SQLException e) { Log.e(TAG, "Failed to connect to database", e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { Log.e(TAG, "Failed to close database connection", e); } } } } } ``` 在上面的代码中,我们创建了一个名为 `DatabaseConnector` 的线程类,并在其 `run()` 方法中启动了一个数据库连接。要启动该线程,只需调用 `DatabaseConnector.start()` 方法即可。 注意:在 Android 应用中启动 MySQL 数据库是不推荐的做法,因为它会增加应用的复杂性和风险。通常情况下,我们应该使用 Web API 或其他远程数据服务来获取数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值