Unity中對SQL資料庫的操作

來源:互聯網
上載者:User

標籤:

在Unity中,我們有時候需要串連資料庫來達到資料的讀取與儲存。而在.NET平台下,ADO.NET為我們提供了公開資料訪問服務的類。用戶端應用程式可以使用ADO.NET來串連到資料來源,並查詢,添加,刪除和更新所包含的資料。

對於ADO.NET,需要瞭解到Connection,Command,DataReader,DataAdapter,DataSet這幾個對象,他們是操作資料庫的重要對象。下面簡要得介紹下這幾個對象的作用以及功能(以SQL為例)。

1、Connection:它是建立應用程式與資料庫之間的串連通道,起到串連資料庫的功能。其訪問形式根據資料庫的類型而定。以SQL為例,則連線類型為SqlConnection。這種串連需要引入相應資料庫的命名空間,這裡我們需要引入System.Data.SqlClient。想要引入這個命名空間還需要System.Data.dll檔案,就在Unity安裝來源目錄下即可找到,複製匯入Unity的Asset即可。
寫法如下:

 

//聲明一個字串用於儲存串連資料庫字串        string s = "server=localhost;database=hasion;uid=sa;pwd=hasion";        SqlConnection con = new SqlConnection(s);        con.Open();

這樣資料庫的串連就開啟了。

2、Command:當應用程式建立與資料來源的串連後,就需要Command對象來執行命令並從資料來源中返回結果。它是一個資料命令對象,主要功能就是向資料庫發送查詢、更新、刪除、修改操作的SQL語句。這邊需要講下它執行SQL的幾種方法:ExecuteNonQuery方法,該方法是返回受影響的行數可用於統計,(如需進行預存程序則需更改CommandType的屬性)。

寫法如下:

//聲明一個字串用於儲存串連資料庫字串        string s = "server=localhost;database=hasion;uid=sa;pwd=hasion";SqlConnection con = new SqlConnection(s);        con.Open();//建立SqlCommand對象,並指定其使用con串連資料庫        SqlCommand cmd = new SqlCommand();        cmd.Connection = con;//設定CommandText,設定其執行SQL語句    cmd.CommandText="update Table_1 set 資產=1000 where 性別=‘女‘";int i = Convert.ToInt32 (cmd.ExecuteNonQuery ());print ("查詢到"+i+"個女性");


ExecuteScalar方法,返回結果集合的第一行的第一列,常用語統計資料數量,用法如下:

//聲明一個字串用於儲存串連資料庫字串        string s = "server=localhost;database=hasion;uid=sa;pwd=hasion";SqlConnection con = new SqlConnection(s);        con.Open();//建立SqlCommand對象,並指定其使用con串連資料庫        SqlCommand cmd = new SqlCommand();        cmd.Connection = con;//設定CommandText,設定其執行SQL語句cmd.CommandText="select * from Table_1 where 性別=‘女‘";int i = Convert.ToInt32 (cmd.ExecuteScalar ());print ("查詢到"+i+"個女性");

 

ExecuteReader方法,返回一個SqlDataReader對象,可進行資料的讀取,其用法如下:

 

//聲明一個字串用於儲存串連資料庫字串        string s = "server=localhost;database=hasion;uid=sa;pwd=hasion";SqlConnection con = new SqlConnection(s);        con.Open();//建立SqlCommand對象,並指定其使用con串連資料庫        SqlCommand cmd = new SqlCommand();        cmd.Connection = con;//設定CommandText,設定其執行SQL語句cmd.CommandText="select * from Table_1";SqlDataReader st = cmd.ExecuteReader ();while (st.Read()) {print(st[0].ToString());}cmd.Dispose ();

上面的功能就是輸出表格第一列的所有內容。

3、DataReader:這個就不做解釋了,就是使用ExecuteReader 中返回的對象,具體形式上面已經寫出。

4、DataAdapter:資料配接器,是DataSet與資料來源之間的橋樑。它有兩種工作形式:一種是通過Command對象執行SQL語句,從資料來源中檢索資料,並將檢索到的資料填充到DataSet對象,還有一種是把對DataSet對象所做的更改寫入資料來源(為了方便,下面以vs的windows應用程式為例來展現其具體用法,因為其DataGridView能夠很好的展現表格式資料)。其第一種用法如下(也就是填充DataSet資料集):

//聲明一個字串用於儲存串連資料庫字串        string s = "server=localhost;database=hasion;uid=sa;pwd=hasion";SqlConnection con = new SqlConnection(s);//建立SqlCommand對象,並指定其使用con串連資料庫SqlCommand cmd = new SqlCommand("select * from Table_1",con);//建立SqlDataAdapter對象SqlDataAdapter sda = new SqlDataAdapter ();//指定Commandsda.SelectCommand = cmd;//建立DataSet對象DataSet ds = new DataSet ();sda.Fill (ds);DataGridView.DataSource = ds.Tables [0];

這裡是使用DataAdapter對象的Fill方法填充DataSet資料集,Fill方法使用Select語句從資料來源中檢索資料。需要注意的是,與Select命令關聯的Connection對象必須有效,但不需要將其開啟。

還有一種用法就是更新資料來源,就是使用DataAdapter的Update方法,可以將DataSet中修改過的資料及時地更新到資料庫中。用法如下:

       SqlConnection con = null;        SqlDataAdapter sda;        DataSet ds;        private void button1_Click(object sender, EventArgs e)        {            con = new SqlConnection("server=localhost;database=hasion;uid=sa;pwd=hasion");            //SqlCommand com = new SqlCommand("select * from Table_1", con);            sda = new SqlDataAdapter("select * from Table_1", con);           // sda.SelectCommand = com;            ds = new DataSet();            sda.Fill(ds, "cs");            dataGridView.DataSource = ds.Tables[0];        }        private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)        {                     //顯示每行資料            textBox1.Text = dataGridView.SelectedCells[0].Value.ToString();            textBox2.Text = dataGridView.SelectedCells[1].Value.ToString();            textBox3.Text = dataGridView.SelectedCells[2].Value.ToString();            textBox4.Text = dataGridView.SelectedCells[3].Value.ToString();                }        private void button2_Click(object sender, EventArgs e)        {            //建立一個DataTable            DataTable dt = ds.Tables["cs"];            //把表機構載入到Table_1中            sda.FillSchema(dt, SchemaType.Mapped);            //建立DataRow,並設定DataRow中的值            DataRow dr = dt.Rows.Find(textBox1.Text.Trim());            dr["sex"] = textBox2.Text.Trim();            dr["age"] = textBox3.Text.Trim();            dr["money"] = textBox4.Text.Trim();            //執行個體化一個SqlCommadnbuilder            SqlCommandBuilder cmb = new SqlCommandBuilder(sda);            //更新資料庫            sda.Update(dt);                    }

這樣就可以對資料庫中的資料進行修改了。

5、DataSet:其實上面已經用到了這個對象,他是整個體系的核心,其資料來源於資料庫或者XML,為了從資料庫中擷取資料,需要使用資料配接器從資料中查詢資料。

C#串連資料庫基本原理和方法就是上面這些了。以上的這些一般在串連資料庫中都會用得到。這些也是我自己通過看書琢磨出來的一些東西,都是基礎的部分,更為複雜的資料庫連接則需要具體情況具體對待。

 

下面舉個例子:是在SQL中建立的一個簡單的表格

 

在Unity中,我們如何將讀取到的資料呈現出來,利用上面的那些完全可以做到。下面貼出主要方法,僅供參考:

 

using UnityEngine;using System.Collections;using System;using System.Data;using System.Data.SqlClient;using System.Data.Common;public class SQLConnection : MonoBehaviour {SqlConnection con=null;SqlDataAdapter sda=null;//接受資料變數private string str;void Start(){//建立串連con = new SqlConnection ("server=localhost;database=hasion;uid=sa;pwd=hasion");//執行sqlsda=new SqlDataAdapter ("select * from Table_1", con);//執行個體化資料集,並寫入查詢到的資料System.Data.DataSet ds = new System.Data.DataSet ();sda.Fill (ds, "table");//按行和列列印出資料for (int i=0; i<ds.Tables[0].Rows.Count; i++) {for(int j=0;j<ds.Tables[0].Columns.Count;j++){str+=ds.Tables[0].Rows[i][j].ToString().Trim()+"    ";if(j==ds.Tables[0].Columns.Count-1){print(str);str="";}}}}}

 

 

指令碼執行之後,會列印出下面的結果:

資料既然能夠呈現出來,我們就可以進行其他進一步的操作了,比如製作表格,程式中的邏輯控制啊 等等很多功能,這些等以後遇到了 在具體問題 具體對待了。

當然sql的語句有很多,增刪改查都可以這樣操作,然後再配合Unity的GUI或者NGUI等等UI製作途徑。能夠很好得做出自己想要的效果。

我總結的基本就這麼多了,有不足的地方歡迎大家批評指正!!!謝謝~~~~~~~~

Unity中對SQL資料庫的操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.