1. 程式人生 > >C#mysql泛型Dao.cs

C#mysql泛型Dao.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;

namespace ConsoleApplication1
{
    class Dao
    {
        private const string connstr = "Server=127.0.0.1;Port=3306;Database=mydata;User Id=root;Password=;Character Set=gbk";

        public static bool login(string username, string password)
        {
            bool b = false;
            using (MySqlConnection conn = new MySqlConnection(connstr))
            {
                using (MySqlCommand cmd = new MySqlCommand("select count(*) from t_user where username = @username, password = @password", conn))
                {
                    cmd.Parameters.AddWithValue("username", username);
                    cmd.Parameters.AddWithValue("password", password);
                    conn.Open();
                    int i = Convert.ToInt32(cmd.ExecuteScalar());
                    if (i >= 1)
                    {
                        b = true;
                    }
                }
            }
            return b;
        }

        public static List<Dictionary<string ,string>> select_t_user(string sql, params MySqlParameter[] msp)
        {
            List<Dictionary<string, string>> ldss = new List<Dictionary<string, string>>();
            using (MySqlConnection conn = new MySqlConnection(connstr))
            {
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    cmd.Parameters.AddRange(msp);
                    conn.Open();
                    using (MySqlDataReader mdr = cmd.ExecuteReader())
                    {
                        while (mdr.Read())
                        {
                            Dictionary<string, string> dss = new Dictionary<string, string>();
                            dss.Add("user_iden", mdr["user_iden"].ToString());
                            dss.Add("user_name", mdr["user_name"].ToString());
                            dss.Add("pass_word", mdr["pass_word"].ToString());
                            ldss.Add(dss);
                        }
                    }
                }
            }
            return ldss;
        }

        public static bool insertUpdateDelete(string sql, params MySqlParameter[] msp)
        {
            bool b = false;
            using (MySqlConnection conn = new MySqlConnection(connstr))
            {
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    cmd.Parameters.AddRange(msp);
                    conn.Open();
                    int i = cmd.ExecuteNonQuery();
                    if (i >= 1)
                    {
                        b = true;
                    }
                }
            }
            return b;
        }
    }
}