C#處理MySQL的增、刪、改、查

C#操做MySQL的增、刪、改、查代碼:數據庫

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace MySQL數據庫操做
{
    class Program
    {
        static void Main(string[] args)
        {
            //connectInfo 儲存哪一個數據庫即Database;哪一個ipDataSource;哪一個端口號port;哪一個數據庫帳號userid;指定數據庫密碼passward;
            string connectInfo = "Database=mygame;Data Source=127.0.0.1;port=3306;userid=root;password=root";
            //建立一個數據庫連接
            MySqlConnection connect = new MySqlConnection(connectInfo);
            //打開數據庫連接
            connect.Open();
            #region 查詢


            //建立數據庫命令,有兩個參數,第一個參數是數據庫操做命令,第二個是數據庫連接
            //MySqlCommand cmd = new MySqlCommand("select * from usersinfo where id_usersinfo = 6", connect);
            //使用讀取命令
            //MySqlDataReader reader = cmd.ExecuteReader();
            //讀取流即:reader.Read(),它返回一個bool值,若是存在,會返回一個true,不存在返回false
            //while (reader.Read())
            //{
            //讀取屬性是username的字符串
            // string username = reader.GetString("username");
            //讀取屬性是password的字符串
            //string password = reader.GetString("password");
            //Console.WriteLine(username + ":" + password);

            // }
            #endregion

            #region 寫入
            //用戶本身定義用戶名和密碼
            //string username = "張曉0坤"; string password = "123456789";
            //這裏的@符號後面跟參數,指的是未知的,使用cmdInsert.Parameters.AddWithValue()在下面賦值。
            //MySqlCommand cmdInsert = new MySqlCommand("insert into usersinfo set username =@usern,password=@pwd", connect);
            //cmdInsert.Parameters.AddWithValue("usern",username);
            //cmdInsert.Parameters.AddWithValue("pwd",password);
            //cmdInsert.ExecuteNonQuery();
            #endregion

            #region 刪除

            //MySqlCommand cmd = new MySqlCommand("delete from usersinfo where id_usersinfo = @id", connect);
            //cmd.Parameters.AddWithValue("id", 3);
            //cmd.ExecuteNonQuery();
            #endregion

            #region 更新
            MySqlCommand cmd = new MySqlCommand("update usersinfo set password = @pwd where id_usersinfo = @id", connect);
            cmd.Parameters.AddWithValue("id", 5);
            cmd.Parameters.AddWithValue("pwd", "123456789kun");
            cmd.ExecuteNonQuery();
            #endregion
            //關閉讀取流
            //reader.Close();
            //關閉連接流
            connect.Close();

            Console.ReadKey();
        }
    }
}
相關文章
相關標籤/搜索