android studio安卓连接mysql数据库方法

 

 

 参考连接:

https://blog.csdn.net/qq_57424643/article/details/123971663?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1-123971663-blog-124277798.pc_relevant_downloadblacklistv1&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1-123971663-blog-124277798.pc_relevant_downloadblacklistv1&utm_relevant_index=2

public class MainActivity extends AppCompatActivity {
 
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Connection.mymysql();
 
    }
 

 

package com.example.myapplication;
import android.util.Log;
import android.widget.Toast;

import java.sql.DriverManager;
//import java.sql.Connection;
//import java.sql.DriverManager;
import java.sql.SQLException;
//import android.util.Log;


public class Connection {
    private static final String TAG = "mysql11111";
    java.sql.Connection conn=null;
    public static void mymysql()
    {
        final Thread thread =new Thread(new Runnable() {
            @Override
            public void run() {

                while (!Thread.interrupted()) {
                    try {
                        Thread.sleep(100);  // 每隔0.1秒尝试连接
                    } catch (InterruptedException e) {
                        Log.e(TAG, e.toString());
                    }

// 1.加载JDBC驱动
                    try {
                        Class.forName("com.mysql.jdbc.Driver");
                        Log.v(TAG, "加载JDBC驱动成功");
                    } catch (ClassNotFoundException e) {
                        Log.e(TAG, "加载JDBC驱动失败");
                        return;
                    }

                    // 2.设置好IP/端口/数据库名/用户名/密码等必要的连接信息
                    String ip = "192.168.10.102";
                    int port = 3306;
                    String dbName = "txw_oqa_db";
                   // String url = "jdbc:mysql://" + ip + ":" + port
                        //    + "/" + dbName+"?useUnicode=true&characterEncoding=utf-8&useSSL=false";
                    String url = "jdbc:mysql://" + ip + ":" + port
                            + "/" + dbName;
                    // 构建连接mysql的字符串
                    String user = "root";
                    String password = "87958868";

                    // 3.连接JDBC
                    try {
                        java.sql.Connection conn = DriverManager.getConnection(url, user, password);

                        Log.d(TAG, "数据库连接成功");
                        conn.close();
                        return;
                    }
                    catch (SQLException e) {
                        Log.e(TAG, e.getMessage());
                    }

                }
            }
        });
        thread.start();



    }

}

 

posted @ 2022-06-15 23:06  txwtech  阅读(836)  评论(0编辑  收藏  举报