C#链接mysql操作类

class DatabaseService
    {
        public MySqlConnection mysql;
        public string DbError;
        public DatabaseService() {
            getMySqlCon();
        }
        public void getMySqlCon()
        {
            String mysqlStr = "Database=ecsdb;Data Source=127.0.0.1;User Id=root;Password=root;pooling=false;CharSet=utf8;port=3306";
            this.mysql = new MySqlConnection(mysqlStr);
        }

        public int Execute(string sql) {
            try {
                this.mysql.Open();
                using (MySqlCommand mySqlCommand = new MySqlCommand(sql, this.mysql))
                {
                    int result = mySqlCommand.ExecuteNonQuery();
                    this.mysql.Close();
                    return result;
                }
            } catch (MySqlException ex) {
                this.DbError = ex.Message.ToString();
                Console.WriteLine(this.DbError);
                return -1;
            }
        
        }
        public DataTable GetDataTable(string SqlString, string TablName)
        {
            try
            {
                this.mysql.Open();
                MySqlDataAdapter Da = new MySqlDataAdapter(SqlString, this.mysql);
                this.mysql.Close();
                DataTable dt = new DataTable(TablName);
                Da.Fill(dt);
                return dt;
            }
            catch (MySqlException ex)
            {
                this.DbError = ex.Message.ToString();
                Console.WriteLine(this.DbError);
                return null;
            }

        }

        public DataSet GetDataSet(string SqlString, string TableName)
        {
            try
            {
                
                this.mysql.Open();
                MySqlDataAdapter Da = new MySqlDataAdapter(SqlString, this.mysql);
                this.mysql.Close();
                DataSet ds = new DataSet();
                Da.Fill(ds, TableName);
                return ds;
            }
            catch (MySqlException ex)
            {
                this.DbError = ex.Message.ToString();
                Console.WriteLine(this.DbError);
                return null;
            }
        }

        public string GetOne(string SqlString)
        {
            string result = null;
            try
            {
                this.mysql.Open();
                MySqlCommand comm = new MySqlCommand(SqlString, this.mysql);
                MySqlDataReader dr = comm.ExecuteReader();
                if (dr.Read())
                {
                    result = dr[0].ToString();
                    this.mysql.Close();
                }
                else
                {
                    result = null;
                    this.mysql.Close();
                }

            }
            catch (MySqlException ex)
            {
                this.DbError = ex.Message.ToString();
            }
            return result;
        }

    }
标签:

发表评论