读了很多博客,说引三个dll文件,但是运行时报错,说存在重复,程序不知道引用哪一个,最后只保留了MySQL.Data.dll文件。版本是:.net 3.5
目前数据库已经可以连接了,但是一直在报这个错。
using UnityEngine;
using System;
using System.Collections;
using System.Data;
using MySql.Data.MySqlClient;
public class CMySql : MonoBehaviour
{
public static MySqlConnection dbConnection;
static string host = "127.0.0.1";
static string id = "root";
static string pwd = "xxx"; //密码
static string database = "unity";//数据库名
static string port = "3306";
static string result = "";
private string strCommand = "select ID from unity ;";
public static DataSet MyObj;
void OnGUI()
{
host = GUILayout.TextField(host, 200, GUILayout.Width(200));
id = GUILayout.TextField(id, 200, GUILayout.Width(200));
pwd = GUILayout.TextField(pwd, 200, GUILayout.Width(200));
if (GUILayout.Button("Test"))//校验按钮
{
//string connectionString = string.Format("Server = {0}; Database = {1}; User ID = {2}; Password = {3};", host, database, id, pwd);
string connectionString = string.Format("Database={0};Data Source={1};User Id={2};Password={3};port={4};charset=utf8", database, host, id, pwd, port);
openSqlConnection(connectionString);
MyObj = GetDataSet(strCommand);
//读取数据函数
ReaderData();
}
GUILayout.Label(result);
}
// On quit
public static void OnApplicationQuit()
{
closeSqlConnection();
}
// Connect to database
private static void openSqlConnection(string connectionString)
{
dbConnection = new MySqlConnection(connectionString);
UnityEngine.Debug.Log("连接前" + dbConnection.State);
dbConnection.Open();
UnityEngine.Debug.Log("服务器连接成功!");
UnityEngine.Debug.Log("连接后" + dbConnection.State);
result = dbConnection.ServerVersion; //获得MySql的版本
}
// Disconnect from database
private static void closeSqlConnection()
{
dbConnection.Close();
dbConnection = null;
}
// MySQL Query
public static void doQuery(string sqlQuery)
{
IDbCommand dbCommand = dbConnection.CreateCommand();
dbCommand.CommandText = sqlQuery;
IDataReader reader = dbCommand.ExecuteReader();
reader.Close();
reader = null;
dbCommand.Dispose();
dbCommand = null;
}
#region Get DataSet
public DataSet GetDataSet(string sqlString)
{
DataSet ds = new DataSet();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(sqlString, dbConnection);
da.Fill(ds);
}
catch (Exception ee)
{
throw new Exception("SQL:" + sqlString + "\n" + ee.Message.ToString());
}
return ds;
}
#endregion
//读取数据函数
void ReaderData()
{
MySqlCommand mySqlCommand = new MySqlCommand("Select * from unity;", dbConnection);
MySqlDataReader reader = mySqlCommand.ExecuteReader();
try
{
while (reader.Read())
{
if (reader.HasRows)
{
print("ID:" + reader.GetInt32(0) + "--Name:" + reader.GetString(1) + "--Sex:" + reader.GetString(2));
}
}
}
catch (Exception)
{
Console.WriteLine("查询失败了!");
}
finally
{
reader.Close();
}
}
}