回帖 Android Studio 连接 MySQL 云端数据库 https://blog.csdn.net/baisedeqingting/article/details/78625078
因为访问网络,所以不要忘了在权限列表AndroidMainfest.xml中添加请求访问网络的权限
<uses-permission android:name="android.permission.INTERNET" />
按照上篇文章添加java连接mysql的驱动程序后,给出一个访问云端数据库的示例项目DBDemo。
示例中的数据库在我的云服务器上,mysql用户名和密码都写在代码里面,希望学习者不要破坏我的数据库或服务器。
项目文件DBDemo下载=》 传送门我的GitHub 若无法正常打开,可能因为gradle配置问题
下面是几个主要的文件,及配图
1、操作数据库的java文件
package cn.wjsay.dbdemo; import android.util.Log; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; public class DBUtils { private static final String TAG = "DBUtils"; private static Connection getConnection(String dbName) { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); //加载驱动 String ip = "139.199.38.177"; conn = DriverManager.getConnection( "jdbc:mysql://" + ip + ":3306/" + dbName, "learner", "learner_password"); } catch (SQLException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } return conn; } public static HashMap<String, String> getUserInfoByName(String name) { HashMap<String, String> map = new HashMap<>(); Connection conn = getConnection("dblearner"); try { Statement st = conn.createStatement(); String sql = "select * from user where name = '" + name + "'"; ResultSet res = st.executeQuery(sql); if (res == null) { return null; } else { int cnt = res.getMetaData().getColumnCount(); //res.last(); int rowCnt = res.getRow(); res.first(); res.next(); for (int i = 1; i <= cnt; ++i) { String field = res.getMetaData().getColumnName(i); map.put(field, res.getString(field)); } conn.close(); st.close(); res.close(); return map; } } catch (Exception e) { e.printStackTrace(); Log.d(TAG, " 数据操作异常"); return null; } } }
2、MainActivity.java主活动文件代码清单
package cn.wjsay.dbdemo; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.HashMap; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; Handler handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message message) { ((TextView)findViewById(R.id.tv_result)).setText((String)message.obj); String str = "查询不存在"; if(message.what == 1) str = "查询成功"; Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show(); return false; } }); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText et_name = findViewById(R.id.et_name); (findViewById(R.id.btn_01)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final String name = et_name.getText().toString().trim(); Log.e(TAG, name); if(name == null || name.equals("")) { Toast.makeText(MainActivity.this,"输入不能为空",Toast.LENGTH_SHORT).show(); } else { new Thread(new Runnable() { @Override public void run() { TextView tv_result = findViewById(R.id.tv_result); HashMap<String, String> mp = DBUtils.getUserInfoByName(name); Message msg = new Message(); if(mp == null) { msg.what = 0; msg.obj = "查询结果,空空如也"; //非UI线程不要试着去操作界面 } else { String ss = new String(); for (String key : mp.keySet()) { ss = ss + key + ":" + mp.get(key) + ";"; } msg.what = 1; msg.obj = ss; } handler.sendMessage(msg); } }).start(); } } }); } }
3、MainActivity所用的界面文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:text="请输入待查询的用户名" android:layout_width="match_parent" android:layout_height="wrap_content" /> <EditText android:id="@+id/et_name" android:layout_marginLeft="60dp" android:hint="请输入alice 或 bob" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:text="查询结果" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/tv_result" android:layout_marginLeft="60dp" android:text="缺省" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="点击获取数据"/> </LinearLayout>数据库名 dblearner, 包含的表 uaer(id int, name char(30), password char(30))
软件界面