当前位置:   article > 正文

基于Navicat Premium实现Android stuio连接MySQL数据库,方法1_android studio数据库连接

android studio数据库连接

1.使用Navicat创建数据库,并创建自己需要的数据表

2.在Android studio中创建一个连接数据库类,也就是新建一个class,具体代码如下:

  1. public class myConnect {
  2. //对应创建的数据库名称、用户名、密码等
  3. private final static String url="jdbc:mysql://10.0.2.2:3306/ArtShare?characterEncoding=UTF-8";
  4. private final static String username="root";
  5. private final static String password="123456";
  6. private Statement mStatement;
  7. private Connection mConnection;
  8. static {
  9. try {
  10. Class.forName("com.mysql.jdbc.Driver");
  11. }catch (ClassNotFoundException e){
  12. System.out.println("加载驱动失败!!"+e.getMessage());
  13. }
  14. }
  15. public Connection getConnection(){
  16. try {
  17. mConnection= DriverManager.getConnection(url,username,password);
  18. } catch (SQLException e) {
  19. System.out.println("生成连接对象失败!!"+e.getMessage());
  20. }
  21. return mConnection;
  22. }
  23. public Statement getStatement(){
  24. try {
  25. mStatement=mConnection.createStatement();
  26. } catch (SQLException e) {
  27. System.out.println("生成statment对象失败!!"+e.getMessage());
  28. }
  29. return mStatement;
  30. }
  31. }

 注意:private final static String url="jdbc:mysql://10.0.2.2:3306/ArtShare?characterEncoding=UTF-8";处的url中的3306为自己数据库的端口号,还有可能会写为url="jdbc:mysql://localhost:3306/ArtShare?characterEncoding=UTF-8";我使用时候会报错,知道原因的可以在评论区留言学习

 3.在Android代码中,在需要的时候使用线程的方式调用数据库类进行数据库的连接和实现相应的数据库操作,代码如下:

  1. new Thread(new Runnable() {
  2. @Override
  3. public void run() {
  4. Connection connection=mdbConnection.getConnection();
  5. System.out.println(connection);
  6. //若需要执行数据库操作,在线程中添加相应的代码
  7. }
  8. }).start();

 还有方法2https://mp.csdn.net/mp_blog/creation/editor/124134566

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/796336
推荐阅读
相关标签
  

闽ICP备14008679号