利用C#直接與MySQL數(shù)據(jù)庫(kù)建立交互

首先導(dǎo)入MySql.Data.dll的引用,我這里使用的C#目標(biāo)框架是.NET Framework 4.5,我的dll程序集擴(kuò)展在下面這個(gè)文件夾中。

C:\Program Files (x86)\MySQL\Connector.NET 6.9\Assemblies\v4.5
Paste_Image.png

然后自行將程序集引用添加到VS當(dāng)中。這時(shí)候我們就可以導(dǎo)入MySql的程序集了

using MySql.Data.MySqlClient;

下面來(lái)看看怎么建立與MySql的連接呢,這里我用的自己創(chuàng)建的數(shù)據(jù)庫(kù)

連接查詢數(shù)據(jù)

static void Read()
        {
//Ip+端口+數(shù)據(jù)庫(kù)名+用戶名+密碼
string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=root;SslMode=none;";
MySqlConnection  conn = new MySqlConnection(connectStr); ;
 try//使用try關(guān)鍵字
            {
                conn.Open();//跟數(shù)據(jù)庫(kù)建立連接,并打開連接
                string sql = "select * from user";//MySql語(yǔ)句,查詢列表內(nèi)容
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                MySqlDataReader reader= cmd.ExecuteReader();//執(zhí)行一些查詢
                //cmd.ExecuteScalar();//執(zhí)行一些查詢,返回一個(gè)單個(gè)的值
                //讀取第一次Read(),ke輸出讀取第一列數(shù)據(jù),如果再Read()一次,可輸出讀取第二列數(shù)據(jù),但是只能讀取第二列數(shù)據(jù)
                //reader.Read();//讀取一列數(shù)據(jù)如果讀取(有數(shù)據(jù))成功,返回True,如果沒(méi)有(數(shù)據(jù)),讀取失敗的話返回false
                while (reader.Read())//使用while循環(huán)可讀取所有user列表里的數(shù)據(jù)
                {
               Console.WriteLine(reader.GetInt32("id") +" "+ reader.GetString("username")+" " + reader.GetString("password"));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                conn.Clone();
            }
}

輸出:

Paste_Image.png

這里要注意了關(guān)于C#與mysql數(shù)據(jù)庫(kù)連接問(wèn)題HResult=0x80004005 ,Message=The host 192.168.47.129 does not support SSL connectio
只要在連接字符串里加上'SslMode = none’,就完美解決了(不管數(shù)據(jù)庫(kù)那邊允不允許使用SSL)

插入數(shù)據(jù)

 static void Insert()//插入
        {
            //Ip+端口+數(shù)據(jù)庫(kù)名+用戶名+密碼
            string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=root;";
            MySqlConnection conn = new MySqlConnection(connectStr); ;
            try
            {
                conn.Open();//跟數(shù)據(jù)庫(kù)建立連接,并打開連接
                string sql = "insert into user(username,password,registerdate) value('ETX','1578','"+DateTime.Now+"')";//DateTime.Now調(diào)用時(shí)間
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                //cmd.ExecuteNonQuery();//插入 刪除 修改
                int result = cmd.ExecuteNonQuery();//插入 刪除 返回值是數(shù)據(jù)庫(kù)中受影響的數(shù)據(jù)的行數(shù)
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                conn.Clone();
            }
        }

插入成功,可以在數(shù)據(jù)庫(kù)列表中看到我們插入的數(shù)據(jù):

Paste_Image.png

修改數(shù)據(jù)和刪除數(shù)據(jù)

修改數(shù)據(jù)/刪除數(shù)據(jù)和插入一樣只不過(guò)是MySql語(yǔ)句換成以下

string sql = "update user set username='mage',password='5535' where id = 9";//修改數(shù)據(jù)
string sql = "delete from user where id=9";//刪除數(shù)據(jù)
Paste_Image.png

Paste_Image.png

SQL常用函數(shù)
1、SQL COUNT(column_name) 語(yǔ)法:

count(column_name) 函數(shù)返回指定列的值的數(shù)目(NULL 不計(jì)入):
例如:
select count(UserName) from user;
可以看到我下面列表里面UserName列有6行數(shù)據(jù),所以這里返回的就是6,
但是如果我有一行UserName為Null,那么就會(huì)返回5

Paste_Image.png

2、SQL AVG() 語(yǔ)法
AVG 函數(shù)返回?cái)?shù)值列的平均值。NULL 值不包括在計(jì)算中。

SELECT AVG(column_name) FROM table_name
例如:
select avg(id) from user;
以上面的圖片為例,AVG函數(shù)返回的值就是id列所有數(shù)值的平均值。平均值為3.5.

其他函數(shù)(可自行去查看):
SQL語(yǔ)法:http://www.w3school.com.cn/sql/sql_func_count.asp

Paste_Image.png

VS里面使用SQL函數(shù)并返回所需的值

OK,那么在SQL數(shù)據(jù)庫(kù)里面能返回這些函數(shù)的值,那么我們?cè)趺醋屗祷氐轿覀兊拇a中呢。下面我們來(lái)看看,例如我們用SQL Count函數(shù)它的返回值就是一個(gè)數(shù)在一行一列中這時(shí)候我們就要用到查詢語(yǔ)句 (返回單一的值)ExecuteScalar.

static void ReadUserCount()
        {
            //Ip+端口+數(shù)據(jù)庫(kù)名+用戶名+密碼
            string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=root;";
            MySqlConnection conn = new MySqlConnection(connectStr); ;
            try
            {
                conn.Open();//跟數(shù)據(jù)庫(kù)建立連接,并打開連接
                string sql = "select count(*) from user";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                object o = cmd.ExecuteScalar();//執(zhí)行查詢,返回單一的值
                int count = Convert.ToInt32(o.ToString());
                Console.WriteLine(count);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                conn.Clone();
            }

        }

這時(shí)候我們就可以看到我們VS里面輸出的結(jié)果是6,因?yàn)槲覀償?shù)據(jù)庫(kù)總共6行.

如何在服務(wù)器端驗(yàn)證客戶端輸入的賬戶密碼

static bool verifyUser(string usernam, string password)
        {
            //Ip+端口+數(shù)據(jù)庫(kù)名+用戶名+密碼
            string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=root;SslMode=none;";
            MySqlConnection conn = new MySqlConnection(connectStr); 
            try
            {
                conn.Open();//跟數(shù)據(jù)庫(kù)建立連接,并打開連接
                //SQL執(zhí)行條件語(yǔ)句,判斷客戶端輸入的賬戶密碼是否與數(shù)據(jù)庫(kù)的相等
                string sql = "select * from user where username = '" + usernam + "' and password='" + password + "'";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                MySqlDataReader reader = cmd.ExecuteReader();
                //判斷是否讀取到判斷的語(yǔ)句,如果讀取到那么說(shuō)明用戶和密碼都正確
                if (reader.Read())
                {
                    return true;
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                conn.Clone();
            }
            return false;
        }

那么這樣就驗(yàn)證成功了


Paste_Image.png

第二種添加數(shù)據(jù)庫(kù)參數(shù)的方式

                string sql = "select * from user where username = @V1 and password=@V2";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("V1",username);
                cmd.Parameters.AddWithValue("V2", password);

安裝MYSQL后我們也會(huì)有一本連接MYSQL的教程,在MYSQL的安裝目錄里面,框出來(lái)的是比較重要的教程
我的連接教程在安裝目錄下的:

C:\Program Files (x86)\MySQL\Connector.NET 6.9\Documentation
Paste_Image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容