之前的配置环节就不在介绍了,主要就是mysql.data.dll的载入操作,假设数据库已经安装完毕,且unity可正常运行。
一、连接
连接好后,这里应该是绿色的。
读取的代码如下:
第一个cs代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MySql.Data.MySqlClient;
using System.Text;
using System.Data;
using System;
public class SqlAccess
{
public static MySqlConnection dbConnection;
static string host = "localhost";
static string port = "3306";
static string username = "root";
static string pwd = "wasd";//输入自己数据库的密码
static string database = "studydb";//输入自己建立的数据库名称
public SqlAccess()
{
OpenSql();
}
public static void OpenSql()
{
try
{
string connectionString = string.Format("server = {0};port={1};user = {2};password = {3};database = {4};", host, port, username, pwd, database);
Debug.Log(connectionString);
dbConnection = new MySqlConnection(connectionString);
Debug.Log("准备建立连接。。。。");
dbConnection.Open();
Debug.Log("建立连接成功");
}
catch (Exception e)
{
throw new Exception("服务器连接失败,请重新检查是否打开mysql服务"+e.Message.ToString());
}
}
public void Close()
{
if (dbConnection!=null)
{
dbConnection.Close();
dbConnection.Dispose();
dbConnection = null;
}
}
public DataSet SelectAll(string tablename)
{
StringBuilder query = new StringBuilder();
query.Append("SELECT * FROM ");
query.Append(tablename);
Debug.Log(query.ToString());//打印sql语句
return ExecuteQuery(query.ToString());
}
public DataSet ExecuteQuery(string SQLString)
{
DataSet ds = new DataSet();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(SQLString, dbConnection);
da.Fill(ds);
}
catch (MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
第二个cs文件如下,命名应为testSql:
using System.Data;
using UnityEngine;
public class TestSql : MonoBehaviour
{
// Start is called before the first frame update
public float timer = 0f;
public void Start()
{
SqlAccess sql = new SqlAccess();
DataSet ds = sql.SelectAll("houcun");//该表需添自己数据库中想要遍历的表的名称
DataTable table = ds.Tables[0];
if (ds != null)
{
foreach (DataRow row in table.Rows)
{
//if (timer >= 1)
//{
// string str1 = "";
// foreach (DataColumn column in table.Columns)
// str1 += row[column] + " ";
// Debug.Log(str1);
// timer = 0f;
//}
string str = "";
foreach (DataColumn column in table.Columns)
str += row[column] + " ";
Debug.Log(str);
}
}
}
void Update()
{
timer += Time.deltaTime;
}
}