unity直接连接数据库

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiajing13579/article/details/78291947

1. 在Unity3D 的安装目录 把    Editor\Data\Mono\lib\mono\unity\System.Data.dll 文件拷被到Assets 文件夹中

2. 在Unity3D 中增加一个  button 


3.在button 上增加一个角本 script 


4. 在 button 中增加 click 事件


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Data;
using System.Data.SqlClient;




using UnityEngine.Events;
using UnityEngine.UI;
public class NewBehaviourScript1 : MonoBehaviour {




public SqlConnection con = null;
public SqlDataAdapter sda = null;  
public int RowIndex = 0;


// Use this for initialization
void Start () {

// 这里的写法 动态的给 button 增加 click 事件,如果不在这里写 则直接 在 unity 中 增加这个 script 后, ,再增加 一个 click 拖动 button到 左边, 再到右连选事件,

// 就为 button 增加了一个事件

//GameObject btnObj = GameObject.Find("Buttonx");
//Button btn = btnObj.GetComponent<Button>();
//btn.onClick.AddListener(delegate() {
// this.Button1_onclick(); 


//});
}


public void Button1_onclick(){
//注意,这里必须使用SQL Server和Windows验证模式,否则会报错 

                //这里要用 127.0.0.1 好像 用 . 没有用.
try{
Debug.Log("hello1");
string s = @"server=127.0.0.1\sqlserver2008;database=FlyNew;uid=sa;pwd=12345";    
con = new SqlConnection(s);
Debug.Log("2");
con.Open(); 
Debug.Log("打开");
string sql = "select * from T2_elderly";        
sda = new SqlDataAdapter(sql, con);        
DataSet ds = new DataSet();        
sda.Fill(ds, "table1");        
print(ds.Tables[0].Rows[RowIndex]["ELderlyName"]); 
this.RowIndex ++;
}catch(Exception ex){
print (ex.ToString());
}
}


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

}
}



猜你喜欢

转载自blog.csdn.net/xiajing13579/article/details/78291947