unity连接mysql增删改查
时间: 2024-12-29 13:10:26 浏览: 21
在Unity中集成MySQL数据库通常涉及到数据持久化,以便存储和检索游戏内的状态信息。以下是一个基本步骤来实现Unity连接到MySQL并完成增删改查操作:
1. **设置环境**:
- 安装必要的库:你可以使用如MySql.Data.NET或Unity MySQL Connector这样的插件,它们提供了.NET支持来连接MySQL。
- 获取数据库凭证:包括服务器地址、端口、数据库名、用户名和密码。
2. **初始化连接**:
```csharp
using MySql.Data.MySqlClient;
MySqlConnection connection = new MySqlConnection("server=localhost;port=3306;database=mygame_db;uid=root;password=mypassword;");
connection.Open();
```
3. **执行SQL命令**:
- 插入数据 (INSERT) :
```csharp
string query = "INSERT INTO Players (Name, Score) VALUES ('PlayerName', 100)";
MySqlCommand command = new MySqlCommand(query, connection);
int result = command.ExecuteNonQuery();
```
- 查询数据 (SELECT) :
```csharp
string selectQuery = "SELECT * FROM Players WHERE Name = 'PlayerName'";
MySqlCommand selCommand = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = selCommand.ExecuteReader();
while (reader.Read())
{
string name = reader.GetString(0); // 读取第0个字段
int score = reader.GetInt32(1);
}
```
- 更新数据 (UPDATE) :
```csharp
string updateQuery = "UPDATE Players SET Score = Score + 50 WHERE Name = 'PlayerName'";
MySqlCommand updCommand = new MySqlCommand(updateQuery, connection);
int rowsAffected = updCommand.ExecuteNonQuery();
```
- 删除数据 (DELETE) :
```csharp
string deleteQuery = "DELETE FROM Players WHERE Name = 'PlayerName'";
MySqlCommand delCommand = new MySqlCommand(deleteQuery, connection);
int deletedRows = delCommand.ExecuteNonQuery();
```
4. **关闭连接**:
- 当不再需要数据库连接时,记得关闭它:
```csharp
connection.Close();
```
阅读全文