unity 查询mysql数据库中某个表的所有数据,之后找出相同的数据
时间: 2024-05-02 21:22:09 浏览: 199
以下是Unity中使用C#查询MySQL数据库中某个表的所有数据,并找出相同数据的示例代码:
```csharp
using System.Collections.Generic;
using MySql.Data.MySqlClient;
public class MySQLManager {
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public MySQLManager() {
server = "localhost";
database = "mydatabase";
uid = "root";
password = "password";
string connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
public List<string> QueryDataFromTable(string tableName) {
List<string> dataList = new List<string>();
string query = "SELECT * FROM " + tableName;
MySqlCommand cmd = new MySqlCommand(query, connection);
try {
connection.Open();
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read()) {
string data = "";
for (int i = 0; i < dataReader.FieldCount; i++) {
data += dataReader[i].ToString() + ",";
}
if (!string.IsNullOrEmpty(data)) {
dataList.Add(data);
}
}
dataReader.Close();
} catch (MySqlException ex) {
Debug.LogError("MySQL Error: " + ex.Message);
} finally {
connection.Close();
}
return dataList;
}
public List<string> FindDuplicateData(List<string> dataList) {
List<string> duplicateList = new List<string>();
HashSet<string> hashSet = new HashSet<string>();
foreach (string data in dataList) {
if (!hashSet.Add(data)) {
duplicateList.Add(data);
}
}
return duplicateList;
}
}
```
使用方法:
```csharp
MySQLManager mySQLManager = new MySQLManager();
List<string> dataList = mySQLManager.QueryDataFromTable("mytable");
List<string> duplicateList = mySQLManager.FindDuplicateData(dataList);
foreach (string data in duplicateList) {
Debug.Log(data);
}
```
在上面的示例代码中,需要根据实际情况修改MySQL数据库连接的相关信息。QueryDataFromTable方法用于查询指定表中的所有数据,并将其放入List<string>中返回。FindDuplicateData方法用于找出相同的数据,并将其放入List<string>中返回。这里使用HashSet来判断是否存在重复数据。最后,使用上述方法可以查询指定表中的所有数据,并找出相同的数据。
阅读全文