【问题标题】:Can not Drivermanager.getConnection(...) in android app无法在 Android 应用程序中使用 Drivermanager.getConnection(...)
【发布时间】:2017-08-17 19:27:58
【问题描述】:

我在从 android 应用程序连接我的数据库时遇到问题。连接的库(mysql-connector-java.5.1.41-bin)已添加到项目中。

连接和插入数据库的功能

public void insert(String SMS_ID, String SMS_ADRESS, String SMS_TEXT, String SMS_CREATOR, String SMS_DATE) throws SQLException {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://192.168.1.14:3306/smschecker";
            Connection c = DriverManager.getConnection(url, "root", "root"); //there it jumps to catch (ClassNotFoundException e)
            PreparedStatement st = c.prepareStatement("insert into SMS values (?,?,?,?,?)");

            st.setString(1, SMS_ID);
            st.setString(2, SMS_ADRESS);
            st.setString(3, SMS_TEXT);
            st.setString(4, SMS_CREATOR);
            st.setString(5, SMS_DATE);

            st.execute();
            st.close();
            c.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

来自 DB GUI 的屏幕截图

http://imgur.com/a/WXmkJ //连接信息

http://imgur.com/a/eFIoa //用户

问题可能出在用户之间,应用程序没有进入数据库的权限,但我不知道如何为我的应用程序添加权限。

【问题讨论】:

  • 我在 NetBeans 中尝试过,一切正常,所以我不明白为什么这在 android studio 中不起作用-_-
  • + 一些来自调试的屏幕imgur.com/a/i98vd

标签: java android mysql android-studio jdbc


【解决方案1】:

根据您在 cmets 中发布的屏幕截图,确定了问题。

Caused by: android.os.NetworkOnMainThreadException

您不能在主线程上执行网络 IO,您可能必须将其移至异步任务或新线程。

希望这会有所帮助!

【讨论】:

  • 当然,这对我有帮助,我昨天在夜间找到了这个解决方案,但非常感谢您的反应!但我现在的问题是,将数据保存到数据库后如何停止线程?还是使用 AsyncTask 的更好方法?我的一些代码是如何使用线程的:pastebin.com/NtdCFL8g
  • imgur.com/a/ZHoF2 有第二个线程的调试器屏幕
  • @fauzt,如果我的回答解决了您的问题,那么您必须考虑接受作为答案!
猜你喜欢
  • 2013-09-28
  • 1970-01-01
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 2015-06-17
  • 2014-07-26
  • 2020-12-01
  • 1970-01-01
相关资源
最近更新 更多