网络编程
位置:首页>> 网络编程>> 数据库>> Unity连接MySQL并读取表格数据的实现代码

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

作者:1eonleonChan  发布时间:2024-01-19 05:20:30 

标签:Unity,MySQL,数据

表格如下:

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

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

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

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

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

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

代码:


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();
   }
}

来源:https://blog.csdn.net/weixin_46840974/article/details/117914326

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com