MySQL C#教程


這是關於MySQL數據庫的C#教程,包含了對MySQL數據庫基本操作;

數據庫訪問組件MySql Connect/NET

MySql Connect/NET是MySQL官方提供給C#的接口,封裝的非常好,操作MySQL就如同操作自家的SQLServer;

MySql Connect/NET

開始程序之旅

數據庫模型層UserEntity.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace AccessOfMysql.Entity
{
    public class MysqlConfig
    {
        //主機
        private string server;
        public string Server
        {
            get
            {
                return server;
            }
            set
            {
                server = value;
            }
        }

        //數據庫
        private string database;
        public string Database
        {
            get
            {
                return database;
            }
            set
            {
                database = value;
            }
        }

        //用戶id
        private string userid;
        public string Userid
        {
            get
            {
                return userid;
            }
            set
            {
                userid = value;
            }
        }

        //密碼
        private string password;
        public string Password
        {
            get
            {
                return password;
            }
            set
            {
                password = value;
            }
        }
    }
    public class UserEntity
    {
        /// <summary>
        /// 用戶id
        /// </summary>
        private uint id;
        public uint Id 
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }
        /// <summary>
        /// 用戶姓名
        /// </summary>
        private string name;
        public string Name 
        {
            get
            {
                return name;
            }
            set 
            {
                name = value;
            }
        }
        /// <summary>
        /// 用戶住址
        /// </summary>
        private string address;
        public string Address
        {
            get
            {
                return address;
            }
            set
            { 
                address = value; 
            }
        }
    }
}

數據庫訪問層UserAccess.cs

using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using AccessOfMysql.Entity;

namespace AccessOfMysql
{
    class UserAccess
    {
        private string connectString;
        
        public UserAccess(string connectString)
        {
            this.connectString = connectString;
        }

        public List<UserEntity> GetUserListFromDb()
        {
            string query = @"SELECT * 
                             FROM t_user";

            List<UserEntity> userEntityList = new List<UserEntity>();

            using (MySqlConnection connection = new MySqlConnection(this.connectString))
            {
                //打開數據庫連接
                connection.Open();

                //創建SqlCommand對象
                MySqlCommand command = new MySqlCommand(query, connection);

                //執行SQL,返回查詢結果
                using (MySqlDataReader dataReader = command.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        UserEntity userEntity = new UserEntity();
                        userEntity.Id = dataReader.GetUInt32(0);
                        userEntity.Name = dataReader.GetString(1);
                        userEntity.Address = dataReader.GetString(2);
                        userEntityList.Add(userEntity);
                    }
                }
            }
            return userEntityList;
        }

        public void InserUserToDb(UserEntity user)
        {
            string query = @"INSERT INTO t_user (name, address) 
                             VALUES (@name, @address)";

            using (MySqlConnection connection = new MySqlConnection(this.connectString))
            {
                //打開數據庫
                connection.Open();

                //創建SqlCommand
                MySqlCommand command = new MySqlCommand(query, connection);

                command.Parameters.AddWithValue("@name", user.Name);
                command.Parameters.AddWithValue("@address", user.Address);
                
                //執行SQL語句,不查詢
                command.ExecuteNonQuery();
            }
        }

        public int GetUserCountFromDb()
        {
            string query = @"SELECT COUNT(*) 
                             FROM t_user";
            using (MySqlConnection connection = new MySqlConnection(connectString))
            {
                //打開數據庫
                connection.Open();

                MySqlCommand command = new MySqlCommand(query, connection);
                //執行SQL,返回條目數
                int count = int.Parse(command.ExecuteScalar().ToString());
                
                return count;
            }
        }
    }
}

主程序Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using AccessOfMysql.Entity;

namespace AccessOfMysql
{
    class Program
    {
        static void Main(string[] args)
        {
           
            //數據庫連接字符串(charset=utf8:解決插入漢字亂碼問題)
            string connectString = "server=127.0.0.1;database=cjtdb;uid=root;pwd=root;charset=utf8";
            UserAccess userAccess = new UserAccess(connectString);
            try
            {
                //取得用戶信息一覽
                List<UserEntity> userEntityList = userAccess.GetUserListFromDb();
                foreach(UserEntity userEntity in userEntityList)
                {
                    Console.WriteLine("id={0}, name={1}, address={2}", 
                        userEntity.Id, userEntity.Name, userEntity.Address);
                }

                //插入用戶信息
                UserEntity user = new UserEntity();
                user.Name = "李小龍";
                user.Address = "上海";
                userAccess.InserUserToDb(user);

                //統計用戶信息總條數
                int count = userAccess.GetUserCountFromDb();
            }
            catch (MySqlException ex)
            {
                Console.WriteLine(ex.ToString());
            }       
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM