帮我封装一个unity连接mysl数据库的函数
时间: 2023-05-18 15:04:45 浏览: 74
好的,以下是一个简单的Unity连接MySQL数据库的函数封装:
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MySql.Data.MySqlClient;
public class MySQLConnector : MonoBehaviour
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
// 初始化连接
public void InitConnection()
{
server = "localhost";
database = "mydatabase";
uid = "username";
password = "password";
string connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
// 打开连接
public bool OpenConnection()
{
if (connection.State == ConnectionState.Open)
{
return true;
}
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
Debug.Log(ex.Message);
return false;
}
}
// 关闭连接
public bool CloseConnection()
{
if (connection.State == ConnectionState.Closed)
{
return true;
}
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
Debug.Log(ex.Message);
return false;
}
}
// 执行查询
public List<string>[] Select(string query)
{
List<string>[] result = new List<string>[2];
result[0] = new List<string>();
result[1] = new List<string>();
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
result[0].Add(dataReader["id"] + "");
result[1].Add(dataReader["name"] + "");
}
dataReader.Close();
CloseConnection();
return result;
}
else
{
return result;
}
}
// 执行插入、更新、删除等操作
public void ExecuteNonQuery(string
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)