一、常用属性

名称 说明
CommandText  获取或设置要对数据源执行的 Transact-SQL 语句、表名或存储过程
CommandTimeout 获取或设置在终止执行命令的尝试并生成错误之前的等待时间
CommandType 获取或设置一个值,该值指示释 CommandText 是SQL语句,存储过程还是表操作
Connection 获取或设置 DbCommand 的此实例使用的 DbConnection
Parameters 获取 DbParameterCollection
Transaction 获取或设置将在其中执行 DbCommand 的 DbTransaction
using MySql.Data.MySqlClient;
using System;
using System.Data.Common;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};",
                                       "localhost", 3306, "wisdompurchase", "root", "1234");
            DbConnection conn = new MySqlConnection(str);    //创建连接
                                                             //连接的数据库名称
            DbCommand cmd = conn.CreateCommand();
            cmd.CommandText = "Update Person Set Name = 'Ado.net修改' WHERE Id = @Id";    //设置操作语句
            //看看默认的发生错误等待时间(秒)
            Console.WriteLine(cmd.CommandTimeout);  //30
            //指明CommandText是SQL语句,存储过程还是表操作。枚举类型,转到定义可看
            Console.WriteLine(cmd.CommandType);   //输出 Text 表示这是一条SQL语句
            //SqlCommand的SqlConnection实例对象
            Console.WriteLine(cmd.Connection.ConnectionString);     //"server=.;database=JunTest;uid=sa;pwd=123";
            //设置参数值
            cmd.Parameters.Add(new MySqlParameter("@Id", 1));
            Console.WriteLine(cmd.Parameters["@Id"].Value);     //输出1

            conn.Open();
            conn.Close();
            Console.ReadKey();
        }
    }
}
View Code

 

二、常用方法

  1、ExecuteNonQuery()  增删改操作

  增、删、改都是这个:

using MySql.Data.MySqlClient;
using System;
using System.Data.Common;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};",
                                       "localhost", 3306, "wisdompurchase", "root", "1234");
            DbConnection conn = new MySqlConnection(str);    //创建连接
                                                             //连接的数据库名称
            DbCommand cmd = conn.CreateCommand();              //创建命令
            cmd.CommandText = "Update t_s_base_user Set realname = '李伟斌' WHERE Id = @Id";    //设置操作语句
            cmd.Parameters.Add(new MySqlParameter("@Id",MySqlDbType.VarChar));    //设置参数值
            cmd.Parameters["@Id"].Value = 1;
            conn.Open();                                        //打开连接
            int i = cmd.ExecuteNonQuery();                      //执行命令,ExecuteNonQuery由名称看出,只能用于非查询语句
            conn.Close();                                       //关闭连接
            Console.WriteLine(i);                               //输出影响行数

            Console.ReadKey();
        }
    }
}
View Code

  2、ExecuteScalar()   返回第一行第一列
  3、ExecuteReader()  创建一个SqlDataReader用于读取数据

using MySql.Data.MySqlClient;
using System;
using System.Data.Common;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};",
                                       "localhost", 3306, "wisdompurchase", "root", "1234");
            DbConnection conn = new MySqlConnection(str);    //创建连接
                                                             //连接的数据库名称
            DbCommand cmd = conn.CreateCommand();              //创建命令
            cmd.CommandText = "SELECT * FROM `t_s_base_user` LIMIT 5";           //设置操作语句
            conn.Open();                                        //打开连接
            //SqlDataReader读取数据
            using (DbDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    Console.WriteLine(reader[0] + ":" + reader[1]);     //输出当前行的第一列,第二列数据
                }
            }

            cmd.CommandText = "SELECT Count(*) FROM `t_s_base_user`";
            object obj = cmd.ExecuteScalar();                   //仅查询第一行第一列
            Console.WriteLine(Convert.ToInt32(obj));
            conn.Close();                                       //关闭连接

            Console.ReadKey();
        }
    }
}
View Code

  4、ExecuteXmlReader()  返回System.XmlReader实例,用于读取SQLServer中的XML字段的值

  首先建一张表如下:

    

/*
SQLyog Ultimate v11.33 (64 bit)
MySQL - 5.7.17-log 
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;

insert into `article` (`ArticleId`, `ArticleInfo`) values('1','<Article><author age=\"30\">张三</author><length>12000</length><price>42</price></Article>');
ArticleSql

  其中ArticleInfo字段的数据类型为xml,值为:

  <Article><author age="30">张三</author><length>12000</length><price>42</price></Article>

  下面,我们使用ExecuteXmlReader()读取出author的值:  

using System;
using System.Data.Common;
using System.IO;
using System.Xml;

namespace ConsoleApp
{
    public static class ExtensionDbCommand
    {
        public static XmlReader ExecuteXmlReader(this DbCommand cmd)
        {
            object obj = cmd.ExecuteScalar();                   //仅查询第一行第一列
            if (obj == null) return null;
            StringReader strRdr = new StringReader(Convert.ToString(obj));
            return XmlReader.Create(strRdr);
        }
    }
}
ExtensionDbCommand
using MySql.Data.MySqlClient;
using System;
using System.Data.Common;
using System.Xml;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};",
                                       "localhost", 3306, "wisdompurchase", "root", "1234");
            DbConnection conn = new MySqlConnection(str);    //创建连接
                                                             //连接的数据库名称
            DbCommand cmd = conn.CreateCommand();              //创建命令
            conn.Open();                                        //打开连接
            cmd.CommandText = "SELECT ArticleInfo FROM Article LIMIT 1";  //查询XML字段
            using (XmlReader reader = cmd.ExecuteXmlReader())           //由Command实例返回XmlReader的实例
            {
                while (reader!=null && reader.Read())
                {
                    if (reader.Name == "author")
                    {
                        Console.WriteLine(reader.ReadInnerXml());       //输出张三
                    }
                }
            }
            conn.Close();
            Console.ReadKey();
        }
    }
}
Program

 还有就是以上这些方法的异步版本,本处仅以以下两个方法示例:

  5、BeginExecuteNonQuery() 异步版ExecuteNonQuery()

  6、EndExecuteNonQuery()  异步版ExecuteNonQuery()

using MySql.Data.MySqlClient;
using System;
using System.Data.Common;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};",
                                       "localhost", 3306, "wisdompurchase", "root", "1234");
            DbConnection conn = new MySqlConnection(str);    //创建连接
                                                             //连接的数据库名称
            MySqlCommand cmd = (MySqlCommand)conn.CreateCommand();                  //创建命令
            cmd.CommandText = "INSERT INTO `article` VALUES(2,'郭嘉')";    //设置操作语句
            conn.Open();                                            //打开连接
            cmd.BeginExecuteNonQuery(BeginCallback, cmd);           //异步执行语句
            Console.WriteLine("不管你执没执行完,我继续做我的事!");

            Console.ReadKey();
        }

         static void BeginCallback(IAsyncResult result)
        {
            Console.WriteLine("正在执行SQL命令!");
            MySqlCommand cmd = result.AsyncState as MySqlCommand;   //获得异步传入的参数
            Console.WriteLine("成功执行命令:" + cmd.CommandText);
            Console.WriteLine("本次执行影响行数为:" + cmd.EndExecuteNonQuery(result));
            Console.WriteLine("关闭连接!");
            cmd.Connection.Close();     //正式关闭连接
        }
    }
}
Program