unity连接MySQL数据库并完成增删改查

数据存储量比较大时,我就需要将数据存储在数据库中方便使用,尤其是制作管理系统时,它的用处就更大了。
在编写程序前,需要在Assets文件夹中创建plugins文件,将.dll文件导入,文件从百度网盘自取:
链接:https://pan.baidu.com/s/1N4xlkh9FP28d8lHylcNe4g
提取码:5zap

连接数据库代码如下:

using UnityEngine;
using MySql.Data.MySqlClient;

public string ConnectStr;
public MySqlConnection conn;

void Start()
{
      ConnectStr = “Server = 192.168.1.25;Database = student;User ID = root;Password = 123456;Port = 8086;charset = utf8”;//数据库所在电脑的IP地址,数据库名称,数据库用户名,用户密码,数据库端口号,采用的编码格式
      conn = new MySqlConnection(ConnectStr);
}

在表中新增信息:

void add()
{
    conn.Open();
    string insertInfo = "insert into user(account_id,account_type,password,name)values(0,0,123456,ling)"
    MysqlCommand insert = new MySqlCommand(insertInfo,conn);
    insert.ExecuteNonQuery();
    conn.Close();
}

如果插入的值为变量,则需将插入语句换为如下:

string insertInfo = "insert into user(account_id,account_type,password,name)values('" + accountId + "','" + accountType + "',123456,ling)";//其他类似

将表中信息删除:

void delete()
{
    conn.Open();
    string deleteInfo = "delete from user where account_id = '" + accountId + "';
    MysqlCommand delete = new MySqlCommand(deleteInfo,conn);
    delete.ExecuteNonQuery();
    conn.Close();
}

将表中信息修改:

void update()
{
    conn.Open();
    string updateInfo = "update user set account_type = '" + accountType + "' where account_id = '" + accountId + "';
    MysqlCommand update = new MySqlCommand(updateInfo,conn);
    update.ExecuteNonQuery();
    conn.Close();
}

将表中信息查询:

void search()
{
    conn.Open();
    string searchInfo = "select *from user where account_id = '" + accountId + "';//查询id号为accountId 的所有信息
    MysqlCommand search = new MySqlCommand(searchInfo,conn);
    MysqlDataReader reader = search.ExecuteReader();
    if(reader.Read())
    {
       string account_id= reader[0];
       string account_type= reader[1];
       string password= reader[2];
       string name= reader[3];
    }
    conn.Close();
}

你可能感兴趣的:(数据库,unity,mysql)