首页 > 数据库 > mysql

Unity连接MySQL并读取表格数据的实现代码

发布时间:2021-6-20 00:00

表格如下:

theTableForm

在Unity读取并调用时的代码:

0

1

而如果想要查看该数据库中的另一个表,不是直接使用Table[1],而是需要更改SELECT * from <?>的表名

调用不同表
成功调用

代码:

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

public class getGameUserAccount : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        mySqlCon();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void mySqlCon()
    {
        //数据库登录数据
        string conStr = "server=localhost;User Id = root;password=123456;Database=gamerdata;charset=utf8";

        //建立连接
        //实例化的同时调用MySqlConnection,传入参数
        //这里的传入参数个人认为是CMD里面的直接输入了,string格式直接类似手敲到cmd里面
        MySqlConnection myCon = new MySqlConnection(conStr);

        //打开连接
        myCon.Open();

        //插入数据,其中useraccount为表名,括号内为表的格式
        /*
        //此处注释是因为不能添加相同主键的值
        MySqlCommand myCmd = new MySqlCommand("insert into useraccount(id,nickname,password) values (4,'list','testList')", myCon);
        if (myCmd.ExecuteNonQuery() > 0)
        {
            Debug.Log("Query Success!");
        }
        */

        //查询数据
        string selStr = "select * from useraccount";
        MySqlCommand mySelect = new MySqlCommand(selStr, myCon);

        DataSet ds = new DataSet();

        try
        {
            MySqlDataAdapter da = new MySqlDataAdapter(selStr, myCon);
            da.Fill(ds);
            
            Debug.Log(ds.Tables[0].Rows[0][0]);
            Debug.Log(ds.Tables[0].Rows[0][1]);
            Debug.Log(ds.Tables[0].Rows[0][2]);
            Debug.Log(ds.Tables[0].Rows[0][3]);

            //Table[0].Rows[0][0]
            Debug.Log("Query Success!");
        }
        catch (Exception e)
        {
            throw new Exception("SQL:" + selStr + "\n" + e.Message.ToString());
        }

        myCon.Close();
    }
}

到此这篇关于Unity连接MySQL时读取表格的方式的文章就介绍到这了,更多相关Unity连接MySQL读取表格内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

标签:[!--infotagslink--]

您可能感兴趣的文章: