|
刚在蛮牛上看到涉及到服务器这块,特意的去网上找了一些资料和自己的一些认知,分享给大家
不多废话,直接上代码:[code=csharp]using UnityEngine;
using System;
using System.Collections;
using System.Data;
using MySql.Data.MySqlClient;
public class CMySql : MonoBehaviour {
// Global variables 全局变量
public static MySqlConnection dbConnection;//Just like MyConn.conn in StoryTools before
//自己的主机地址
static string host = "192.168.1.100";
static string id = "mysql";//这里是你自己的数据库的用户名字,我一开始想用root,发现不行,后来添加了新的用户才可以
//数据库密码
static string pwd = "123456";
//数据库名称
static string database = "test";
//定义一个空字符串
static string result = "";
//数据库查询语句
private string strCommand = "Select * from unity3d_test ORDER BY id;";
//dataset这个是MySql.Data.MySqlClient.dll库中自带的类型
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);
openSqlConnection(connectionString);
MyObj = GetDataSet(strCommand);
}
GUILayout.Label(result);
}
// On quit
public static void OnApplicationQuit() {
closeSqlConnection();
}
// Connect to database
private static void openSqlConnection(string connectionString) {
dbConnection = new MySqlConnection(connectionString);
dbConnection.Open();
result = dbConnection.ServerVersion;
//Debug.Log("Connected to database."+result);
}
// Disconnect from database
private static void closeSqlConnection() {
dbConnection.Close();
dbConnection = null;
//Debug.Log("Disconnected from database."+result);
}
// 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)
{
//string sql = UnicodeAndANSI.UnicodeAndANSI.UnicodeToUtf8(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
}[/code]
|
|