Unity是一款跨平台的游戏引擎,常用于游戏开发和虚拟现实应用的创建。MySQL是一种关系型数据库管理系统,用于存储和管理数据。在Unity中查询MySQL数据库可以通过以下步骤实现:
using System.Data;
using MySql.Data.MySqlClient;
public class DatabaseManager
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public DatabaseManager()
{
server = "localhost";
database = "your_database_name";
uid = "your_username";
password = "your_password";
string connectionString = "Server=" + server + ";Database=" + database + ";Uid=" + uid + ";Pwd=" + password + ";";
connection = new MySqlConnection(connectionString);
}
public void OpenConnection()
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
}
public void CloseConnection()
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
public DataTable Select(string query)
{
OpenConnection();
MySqlCommand command = new MySqlCommand(query, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
CloseConnection();
return dataTable;
}
}
public DataTable SelectAllUsers()
{
string query = "SELECT * FROM users";
return Select(query);
}
DatabaseManager databaseManager = new DatabaseManager();
DataTable usersData = databaseManager.SelectAllUsers();
foreach (DataRow row in usersData.Rows)
{
string username = row["username"].ToString();
int score = int.Parse(row["score"].ToString());
// 进行后续操作
}
需要注意的是,在使用Unity连接MySQL数据库时,你需要确保已经正确安装和配置了MySQL Connector/Net,并且数据库服务器处于运行状态。此外,还需要注意数据库安全,避免在客户端直接执行敏感操作,应通过服务端或中间层来处理和验证数据。
领取专属 10元无门槛券
手把手带您无忧上云