沒有阿里云資料庫的可以買個最便宜的,我是新用戶9.9元買了一個
1.買到后點擊左上角的作業臺

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

開始寫Android Studio專案代碼了,先來看看我的專案結構

依賴包下載地址 Central Repository: mysql/mysql-connector-java (maven.org)
我第一次下了個版本比較新的發現會報錯,由于我能力有限,所以就老實下載一個低版本的
添加依賴包應該都會了吧,不要忘了添加后還要添加到模塊

MainActivity代碼如下
注意代碼里涉及SQL陳述句,這里要根據你之前新建的資料庫和新建的表來寫,我新建的表是test
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MainActivity extends AppCompatActivity {
private TextView t1; //用于顯示獲取的資訊
private Button sendmsg; //發送訊息按鈕
private EditText et_msg;//用戶輸入資訊框
private String user="user"; //默認用戶昵稱
private boolean T=false;//發送標志位
//資料庫連接類物件
private static Connection con = null;
private static PreparedStatement stmt = null;
private Button revise;
private EditText et_revise;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化
t1 = findViewById(R.id.t1);
et_msg = findViewById(R.id.msg);
et_revise = findViewById(R.id.reviseText);
sendmsg = findViewById(R.id.button);
revise = findViewById(R.id.revise);
revise.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
user = et_revise.getText().toString();
Toast.makeText(MainActivity.this,"修改成功",Toast.LENGTH_SHORT).show();
}
});
sendmsg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { T=true; }
});
//TODO 啟動發送執行緒,用按鈕控制發送標志位T,來進行發送資訊【注意:連接資料庫必須在執行緒內,不然會報錯】
Threads_sendmsg threads_sendmsg = new Threads_sendmsg();
threads_sendmsg.start();
//TODO 啟動獲取資料執行緒,讀取資料庫里的資訊【注意:連接資料庫必須在執行緒內,不然會報錯】
Threads_readSQL threads_readSQL = new Threads_readSQL();
threads_readSQL.start();
}
class Threads_sendmsg extends Thread {
@Override
public void run() {
while (true){
while (T){
try {
con = MySQLConnections.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
try {
//注意你資料庫中是否有 test 這個表,我新建的表是 test
//還有我的屬性,是否和我一樣呢,不一樣就按你自己的來吧
String msg =et_msg.getText().toString().trim(); //用戶發送的資訊
if (msg.isEmpty()){
Looper.prepare();
Toast.makeText(MainActivity.this, "訊息為空", Toast.LENGTH_SHORT).show();
Looper.loop();
T=false;
break;
}
if (msg.length()>199){
Looper.prepare();
Toast.makeText(MainActivity.this, "訊息長度超過限制", Toast.LENGTH_SHORT).show();
Looper.loop();
T=false;
break;
}
if (con!=null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "發送成功", Toast.LENGTH_SHORT).show();
}
});
String sql = "insert into test(name,msg,sign) values(?,?,?)";
stmt = con.prepareStatement(sql);
// 關閉事務自動提交 ,這一行必須加上
con.setAutoCommit(false);
stmt.setString(1,user);
stmt.setString(2,msg);
stmt.setInt(3,1);
stmt.addBatch();
stmt.executeBatch();
con.commit();
}
}catch (SQLException e){
System.out.println(e);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,"請輸入正確的陳述句",Toast.LENGTH_SHORT).show();
}
});
}
T=false;
}
}
}
}
class Threads_readSQL extends Thread {
ResultSet rs;
@Override
public void run() {
while (true) {
try {
con = MySQLConnections.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
try {
//注意你資料庫中是否有 test 這個表,我新建的表是 test
//還有我的屬性,是否和我一樣呢,不一樣就按你自己的來吧
String sql = "select name,msg,sign from test";
if (con != null) {
stmt = con.prepareStatement(sql);
// 關閉事務自動提交
con.setAutoCommit(false);
rs = stmt.executeQuery();//創建資料物件
//清空上次發送的資訊
t1.setText(null);
while (rs.next() ) {
t1.append(rs.getString(1) + "\n" + rs.getString(2) + "\n\n");
}
con.commit();
rs.close();
stmt.close();
}
//2秒更新一次
sleep(2000);
} catch (Exception e) {
System.out.println(e);
runOnUiThread(new Runnable() {
@Override
public void run() {
//Toast.makeText(MainActivity.this,"請輸入正確的陳述句",Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
}
MainActivity布局檔案activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
// An highlighted block
<TextView
android:id="@+id/t1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="10"
android:text="Hello World!"
android:layout_marginLeft="8dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<EditText
android:id="@+id/reviseText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="請輸入你的昵稱"
android:inputType="textPersonName" />
<Button
android:id="@+id/revise"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="修改" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<EditText
android:id="@+id/msg"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:ems="10"
android:hint="請輸入內容"
android:inputType="textPersonName" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="發送" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
MYSQLConnections代碼如下
注意我寫的注釋,用戶名,密碼,外網地址,外網埠號,資料庫名稱,這些都要填寫你自己的
import java.sql.Connection;
import java.sql.DriverManager;
public class MySQLConnections {
private String driver = "";
private String dbURL = "";
private String user = "";
private String password = "";
private static MySQLConnections connection = null;
private MySQLConnections() throws Exception {
driver = "com.mysql.jdbc.Driver"; //這里根據你下載的依賴包版本會有不同的寫法,下載低版本的就是這樣寫
//rm-bp1lxt0mjpf6o.mysql.rds.aliyuncs.com:3306 這個是外網地址,3306是外網埠號,這些都需要填寫你自己的
//sqlconsole 這個是你登錄你的資料庫后新建的資料庫(應該不繞口吧)
dbURL = "jdbc:mysql://rm-bp1lxt0m.mysql.rds.aliyuncs.com:3306/sqlconsole";
user = "user"; //你新建庫時的用戶名
password = "123456"; //你新建庫時的密碼,這里我就不寫我的真密碼了
System.out.println("dbURL:" + dbURL);
}
public static Connection getConnection() {
Connection conn = null;
if (connection == null) {
try {
connection = new MySQLConnections();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
try {
Class.forName(connection.driver);
conn = DriverManager.getConnection(connection.dbURL,
connection.user, connection.password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
AndroidManifest.xml
注意這里要添加網路請求權限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mysqlconnections">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication1">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
最后看我運行結果
Android Studio和阿里云資料庫
參考博客
Android Studio 連接阿里云資料庫【制作基于資料庫的多人遠程聊天APP】
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/354678.html
標籤:其他
上一篇:Flutter 容器類組件
