当前位置:   article > 正文

Android Studio中实现连接mysql数据库_android studio entry name 'com/mysql/jdbc/configs/

android studio entry name 'com/mysql/jdbc/configs/maxperformance.properties

第一步,前置工作:

1.配置AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

2.配置build.gradle,这一步如果不写后面写静态方法后执行时会报错

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    compileSdkVersion 30
    buildToolsVersion "30.0.0"

3.下载驱动包mysql-connector-java-5.1.49.jar然后复制进libs后add library

这里是个大坑,我之前试过用匹配数据库的版本包8.0.17但一直报错,换成这个版本后就成功连接了

第二步,编程工作

public class DBunit {
    private static String TAG = "rime";
    private static final String dbName = "test";
        /*ip为数据库所在服务器的ip地址*/
    private static final String ip = "192.168.1.7";
    private static final String port = "3306";
    private static String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbName;
    private static final String user = "root";
    private static final String password = "root";

    public static void connectSQL()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Connection conn = null;
                try
                {
                    Class.forName("com.mysql.jdbc.Driver");
                    Log.d(TAG,"驱动加载成功");
                    conn = DriverManager.getConnection(url,user,password);
                    Log.d(TAG,"数据库连接成功");
                    String sql="select name from student";
                    Statement st=(Statement)conn.createStatement();
                    ResultSet rs=st.executeQuery(sql);
                    while(rs.next()){
                        String name=rs.getString("name");
                        Log.i("Mainactivity",name);
                    }
                    conn.close();
                    st.close();
                    rs.close();
                } catch (ClassNotFoundException | SQLException e) {
                    e.printStackTrace();
                    Log.d(TAG,"数据库连接失败");
                }
            }
        }).start();
    }
}
注意事项:数据库连接的代码必须写在新开辟的线程里。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/279710
推荐阅读
相关标签