准备
官方文档示例
- MySqlConnectionStringBuilder 连接相关设置
- MySqlException Sql异常
- MySqlConnection 打开数据库 关闭数据库
- MySqlCommand Sql命令
ExecuteReader 查询数据
ExecuteNonQuery 插入 更新 删除数据
ExecuteScalar 返回操作结果第一行第一列数据,可查询,插入,更新,删除
示例
using MySql.Data.MySqlClient;
using System.Data;
using UnityEngine;
public class ConnectMySql : MonoBehaviour
{
MySqlConnectionStringBuilder mySqlConnectionString = new MySqlConnectionStringBuilder()
{
Server = "localhost",
Port = 3306,
UserID = "root",
Password = "root",
Database = "student"
};
MySqlConnection mySqlConnection;
void Start()
{
mySqlConnection = new MySqlConnection(mySqlConnectionString.ConnectionString);
try
{
mySqlConnection.Open();
}
catch (MySqlException e)
{
Debug.Log(string.Format("错误信息:{0},\n错误编码:{1}", e.Message, e.Number));
}
}
private void OnGUI()
{
if (GUILayout.Button("查询"))
{
if (mySqlConnection.State == ConnectionState.Open)
{
MySqlCommand command = new MySqlCommand("select * from new_table", mySqlConnection);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var info = (reader[0], reader[1], reader[2]).ToString();
Debug.Log(info);
}
reader.Close();
}
}
if (GUILayout.Button("插入"))
{
if (mySqlConnection.State == ConnectionState.Open)
{
string sql = "INSERT INTO new_table(id,name,age) Values (7,'赤色','65')";
MySqlCommand insertCommand = new MySqlCommand(sql, mySqlConnection);
Debug.Log(insertCommand.ExecuteNonQuery());
}
}
if (GUILayout.Button("更新"))
{
if (mySqlConnection.State == ConnectionState.Open)
{
string sql = "UPDATE new_table SET name='赤',age=12 WHERE id=7";
MySqlCommand command = new MySqlCommand(sql, mySqlConnection);
Debug.Log(command.ExecuteNonQuery());
}
}
if (GUILayout.Button("删除"))
{
if (mySqlConnection.State == ConnectionState.Open)
{
string sql = "DELETE FROM new_table WHERE id=7";
MySqlCommand command = new MySqlCommand(sql, mySqlConnection);
Debug.Log(command.ExecuteNonQuery());
}
}
if (GUILayout.Button("查询表中首个id"))
{
if (mySqlConnection.State == ConnectionState.Open)
{
string sql = "SELECT * FROM new_table";
MySqlCommand command = new MySqlCommand(sql, mySqlConnection);
object result = command.ExecuteScalar();
Debug.Log(result);
}
}
}
private void OnDestroy()
{
if (mySqlConnection != null)
mySqlConnection.Close();
}
}