Home Database Mysql Tutorial Can android use mysql?

Can android use mysql?

May 07, 2019 pm 05:11 PM
android mysql

Android can use the mysql database. There are two ways for Android to connect to the database, namely: 1. By connecting to the server, and then the server reads the database to realize the addition, deletion, modification and query of data; 2. Loading the external jar package , directly connect to the database.

Can android use mysql?

android can use the mysql database. There are two ways for android to connect to the database.

The first is to connect to the server and then have the server read the database to add, delete, modify and check data. This is also our common method.

The second method is for Android to directly connect to the database. This method consumes a lot of mobile phone memory and is easily decompiled, causing security risks. Therefore, it is not recommended in actual projects.

1. Load external jar package

If you want to use jdbc in the Android project, you must import the external jar package of jdbc, because there is no jdbc api in Java's jdk. I use The jar package is mysql-connector-java-5.1.18-bin.jar package. There are mysql-connector-java-5.1.18-bin.jar package on the Internet. When I tried to use it myself, I found it was incompatible, so I downloaded it. For newer versions, the jar package can be downloaded from the official website or from Baidu. There are many uploaded by predecessors.

2. How to import the jar package

Method 1:

You can directly add the following statement to the project's build.gradle file to import

compile files('libs/mysql-connector-java-5.1.18-bin.jar')
Copy after login

method Two: Download the jar package and copy it to the libs directory of the project, then right-click the copied jar package Add as libs

3. Establish a database connection

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_jdbc);
    new Thread(runnable).start();
}
Handler myHandler=new Handler(){
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        Bundle data=new Bundle();
        data=msg.getData();
        //System.out.println("id:"+data.get("id").toString());    //输出第n行,列名为“id”的值
        Log.e("TAG","id:"+data.get("id").toString());
       TextView tv= (TextView) findViewById(R.id.jdbc);
        //System.out.println("content:"+data.get("content").toString());
    }
};
Runnable runnable=new Runnable() {
    private Connection con = null;
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //引用代码此处需要修改,address为数据IP,Port为端口号,DBName为数据名称,UserName为数据库登录账户,Password为数据库登录密码
            con =
                    //DriverManager.getConnection("jdbc:mysql://192.168.1.202:3306/b2b", "root", "");
            DriverManager.getConnection("jdbc:mysql://http://192.168.1.100/phpmyadmin/index.php:8086/b2b",
                    UserName,Password);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            testConnection(con);    //测试数据库连接
        } catch (java.sql.SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void testConnection(Connection con1) throws java.sql.SQLException {
        try {
            String sql = "select * from ecs_users";        //查询表名为“oner_alarm”的所有内容
            Statement stmt = con1.createStatement();        //创建Statement
            ResultSet rs = stmt.executeQuery(sql);          //ResultSet类似Cursor
            //<code>ResultSet</code>最初指向第一行
            Bundle bundle=new Bundle();
            while (rs.next()) {
                bundle.clear();
                bundle.putString("id",rs.getString("userid"));
                //bundle.putString("content",rs.getString("content"));
                Message msg=new Message();
                msg.setData(bundle);
                myHandler.sendMessage(msg);
            }
            rs.close();
            stmt.close();
        } catch (SQLException e) {
        } finally {
            if (con1 != null)
                try {
                    con1.close();
                } catch (SQLException e) {}
        }
    }
};
Copy after login

Note:

In After Android 4.0, time-consuming operations are not allowed in the main thread (connecting to the database is a time-consuming operation). A new thread needs to be opened to handle such time-consuming operations. When there is no new thread, the operation is always Just exit the program directly and open a new thread to handle it directly, and there will be no problem.

Of course, connecting to the database requires a network. Don’t forget to add network access permissions:

<uses-permission android:name=”android.permission.INTERNET”/>
Copy after login

Four. Bug points

1. The imported jar package must be Correct

2. A new thread must be opened to connect to the database

3. The IP of the database must be pingable, and the LAN address cannot be accessed by mobile phone

4. Database Is the server where the server is located has a firewall that blocks access?

The above is the detailed content of Can android use mysql?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the &quot;MySQL Native Password&quot; plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

Oppo Find X8 design looks like a cross between Apple iPhone 16 Pro and OnePlus Open in early images Oppo Find X8 design looks like a cross between Apple iPhone 16 Pro and OnePlus Open in early images Sep 28, 2024 am 06:04 AM

Historically, Oppo has refreshed its flagship 'Find X' series in late winter or early spring, save for the original Find X that it announced in June 2018. To that end, the Find X7 and Find X7 Ultra are barely more than six months old at this point. H

Samsung Galaxy Z Fold Special Edition revealed to land in late October as conflicting name emerges Samsung Galaxy Z Fold Special Edition revealed to land in late October as conflicting name emerges Oct 01, 2024 am 06:21 AM

The launch of Samsung's long-awaited 'Special Edition' foldable has taken another twist. In recent weeks, rumours about the so-called Galaxy Z Fold Special Edition went rather quiet. Instead, the focus has shifted to the Galaxy S25 series, including

iQOO Z9 Turbo+ debuts as Dimensity 9300+ smartphone with \'off-the-charts\' battery life iQOO Z9 Turbo+ debuts as Dimensity 9300+ smartphone with \'off-the-charts\' battery life Sep 26, 2024 am 06:20 AM

TheZ9 Turbo+has now been unleashed on Vivo's online Chinese store at 2,199 yuan (~$313) for a 12GB RAM/256GB internal storage base model, whereas theRedmiK70 Extreme Editionstarted at 2,599 yuan (~$370) with the same configuration: in fact, its newiQ

Lenovo reveals new color option for the 2024 Legion Y700 gaming tablet Lenovo reveals new color option for the 2024 Legion Y700 gaming tablet Sep 29, 2024 am 06:05 AM

Lenovo is gearing up to launch the 2024 Legion Y700 on September 29 in China. This new Android gaming tablet will be going against the RedMagic Nova, and the company has already confirmed almost all the specs of the device. Now, hours before the full

Monitoring Redis Droplets Using Redis Exporter Service Monitoring Redis Droplets Using Redis Exporter Service Jan 06, 2025 am 10:19 AM

Effective monitoring of Redis databases is essential for maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a robust utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you establish a monitoring solution seamlessly. By following this tutorial, you’ll achieve a fully operational monitoring setup to effectively monitor the performance metrics of your Redis database.

Java for Mobile Apps: Your First Steps in Android Development Java for Mobile Apps: Your First Steps in Android Development Oct 10, 2024 pm 01:34 PM

Clear answer: Java is the basic language for Android application development. Through the Java development environment and SDK, you can write and run Android applications. Detailed description: Set up the development environment: install Android Studio, JDK and create AVD. Create your first Android application: Use Android Studio to create a project and write Java code for interaction. Define the user interface: Use XML files to create activity layouts and display components. Run your app: Use an emulator or a physical device to run your app. Practical example: Add interactive elements, such as buttons, for a richer user experience.

See all articles