unityMYSQL数据库连接:

using MySql.Data.MySqlClient;
using System;
using System.Data;
using UnityEngine;

public class Test : MonoBehaviour
{

public MySqlConnection mysql;
static string host = "localhost";
static string port = "3306";
static string username = "root";
static string pwd = "123456";
static string database = "gametest";

void Start()
{
    OpenSQL();
}
//连接数据库
public void OpenSQL()
{
    //建立连接语句
    string constr = string.Format("server = {0};port={1};database = {2};user = {3};password = {4};charset=utf8;", host, port, database, username, pwd);
    //建立连接
    mysql = new MySqlConnection(constr);
    //打开连接
    mysql.Open();
}

//查询,读取数据
public void Search(string tableName)
{
    //sql命令,选择gametest表
    string sqlString = "select * from " + tableName;
    MySqlCommand cmd = new MySqlCommand(sqlString, mysql);
    MySqlDataReader reader = cmd.ExecuteReader();
    //Read一次就是一行数据,Read不为空执行打印数据
    while (reader.Read())
    {
        Debug.Log("查询数据:" + reader[0] + "  " + reader[1] + "   " + reader[2]);
    }    reader.Close();
}

//添加数据
public void AddData(int id, int level, string name)
{
    //在表player中添加ID = id,LV = level,Name = name
    string sql = "insert into player(ID,LV,Name) values('" + id + "','" + level + "','" + name + "')";
    MySqlCommand cmd = new MySqlCommand(sql, mysql);
    //返回更改数据行数
    int result = cmd.ExecuteNonQuery();
    Debug.Log("添加数据成功:" + result);

}
//更新数据
public void UpdateData()
{
    //更新表player中ID = 2的数据 ,设置LV = 9,Name = zhang
    string sql = "update player set LV='9',Name='zhang' where ID=2";//更改的sql命令
    MySqlCommand cmd = new MySqlCommand(sql, mysql);
    //返回值是数据库中修改的行数
    int result = cmd.ExecuteNonQuery();
    Debug.Log("更新数据成功:" + result);

}
//删除数据
public void DeleteData()
{
    //删除的sql命令,这里是删除player中id=20的一行数据
    string sql = "delete from player where ID=2";
    MySqlCommand cmd = new MySqlCommand(sql, mysql);
    int result = cmd.ExecuteNonQuery();
    Debug.Log("删除数据成功:" + result);
}

/// <summary>
/// 关闭数据库连接
/// </summary>
public void Close()
{
    if (mysql != null)
    {
        mysql.Close();
        mysql.Dispose();
        mysql = null;
    }
}

}