MySQL数据库的准备

详情可参考以下文章:

命令行客户端MySQL基本命令的使用

python 代码部署数据库

首先运行python代码:

from flask import Flask, jsonify, request
import pymysql

app = Flask(__name__)

# 配置数据库连接信息
DATABASE = {
'host': '',
'user': 'your_user',
'password': 'your_password',
'database': 'your_db'
}

# 连接数据库
def get_db():
conn = pymysql.connect(**DATABASE)
return conn

# 根路径路由
@app.route('/', methods=['GET'])
def index():
return "Welcome to the API!"


@app.route('/get_students', methods=['GET'])
def get_students():
conn = pymysql.connect(host='', user='your_user', password='your_password', database='your_db')
cursor = conn.cursor()
sql = "SELECT * FROM students"
cursor.execute(sql)
results = cursor.fetchall()
cursor.close()
conn.close()

# Convert the results to a list of dictionaries
students_list = []
for row in results:
student_dict = {
'id': row[0],
'name': row[1],
'age': row[2]
# Add more fields as needed
}
students_list.append(student_dict)

# Return the JSON response
return jsonify(students_list)
# return jsonify(students)

if __name__ == '__main__':
app.run(debug=True)

运行成功以后会显示:

 python 'try1_sql.py'
* Serving Flask app 'try1_sql'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
* Debugger PIN: 678-850-224

Unity 脚本配置

Unity canvas 显示界面

1、首先创建如图的canvas界面:

image-20240817123306070

2、 如果数据库中出现中文,则需要导入中文字体并在TextMeshPro文本框中配置

3、创建一个名为ApiCaller.cs的脚本,并创建一个名为ApiCaller的空物体

以下为ApiCaller.cs的具体内容:

using UnityEngine;
using UnityEngine.Networking;
using TMPro;
using System.Collections;
using System.Collections.Generic;

public class ApiCaller : MonoBehaviour
{
public TextMeshProUGUI text1;
public TextMeshProUGUI text2;
public TextMeshProUGUI text3;
public TextMeshProUGUI text4;

private string baseUrl = "http://127.0.0.1:5000"; // 你的 Flask API 的地址

void Start()
{
StartCoroutine(TestApiConnection());
}

IEnumerator TestApiConnection()
{
using (UnityWebRequest request = UnityWebRequest.Get(baseUrl + "/get_students"))
{
yield return request.SendWebRequest();

if (request.result != UnityWebRequest.Result.Success)
{
Debug.Log("Failed to connect to the API. Error: " + request.error);
}
else
{
string response = request.downloadHandler.text;

var students = JsonHelper.FromJson<Student>(response);

if (students != null && students.Length >= 4)
{
AdjustTextSize(text1, students[0].name + ", Age: " + students[0].age);
AdjustTextSize(text2, students[1].name + ", Age: " + students[1].age);
AdjustTextSize(text3, students[2].name + ", Age: " + students[2].age);
AdjustTextSize(text4, students[3].name + ", Age: " + students[3].age);
}
else
{
Debug.Log("Not enough students data in the response.");
}
}
}
}

void AdjustTextSize(TextMeshProUGUI text, string content)
{
text.text = content;

// Reset font size to default
text.fontSize = 36;

// Check if content fits in one line
float preferredWidth = text.GetPreferredValues(content).x;
float rectWidth = text.rectTransform.rect.width;

if (preferredWidth > rectWidth)
{
// Reduce font size to fit in one line
float scaleFactor = rectWidth / preferredWidth;
text.fontSize = (int)(text.fontSize * scaleFactor);
}
}

[System.Serializable]
public class Student
{
public string name;
public int age;
}

public class JsonHelper
{
public static T[] FromJson<T>(string json)
{
string newJson = "{ \"array\": " + json + "}";
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(newJson);
return wrapper.array;
}

[System.Serializable]
private class Wrapper<T>
{
public T[] array;
}
}
}

4、在ApiCaller空物体上挂载该脚本,并在Inspector界面中配置需要显示文字的文本框

5、运行

成功的话终端中会显示如下:

127.0.0.1 - - [17/Aug/2024 12:38:52] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [17/Aug/2024 12:38:52] "GET /get_students HTTP/1.1" 200 -