原文书籍:《C#从入门到精通》
Command对象是一个数据命令对象,主要功能是向数据库发送查询、更新、删除、修改操作的SQL语句。
1、设置数据源类型
Command对象有3个重要的属性:
1、Connection
2、CommandText
3、CommandType
Connection属性用于设置SqlCommand使用的SqlConnection。
CommandText属性用于设置要对数据源执行的SQL 语句或存储过程。
CommandType属性用于设置指定CommandText的类型。
CommandType属性的值是CommandType枚举值,CommandType枚举有3个枚举成员。
1、StoredProcedure:存储过程的名称
2、TableDirect:表的名称
3、Text:SQL文本命令
如果要设置数据源的类型,则可以通过设置CommandType属性来实现。
public partial class Form1 : Form
{
SqlConnection conn; //声明一个SqlConnection变量
public Form1()
{
InitializeComponent();
conn = new SqlConnection("server=.;database=Test;uid=sa;pwd=123"); //实例化SqlConnection变量
conn.Open(); //打开连接
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (conn.State == ConnectionState.Open || textBox1.Text != "")
{
SqlCommand cmd = new SqlCommand(); //创建一个SqlCommand对象
cmd.Connection = conn; //设置Connection属性
cmd.CommandText = "SELECT count(*) FROM " + textBox1.Text.Trim(); //设置CommandText属性,以及SQL语句
cmd.CommandType = CommandType.Text; //SQL文本命令
int i = Convert.ToInt32(cmd.ExecuteScalar()); //使用ExecuteScalar方法获取指定数据表中的数据数量
label2.Text = "数据表中共有:" + i.ToString() + "条数据";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
ExecuteNonQuery方法
执行SQL语句,并返回受影响的行数,在使用SqlCommand向数据库发送增、删、改命令时,通常使用ExecuteNonQuery方法执行发送的SQL语句。
SqlConnection conn; //声明一个SqlConnection变量
private void button1_Click(object sender, EventArgs e)
{
conn = new SqlConnection("server=.;database=Test;uid=sa;pwd=123"); //实例化SqlConnection变量
conn.Open(); //打开连接
SqlCommand cmd = new SqlCommand(); //创建一个SqlCommand对象
cmd.Connection = conn; //设置Connection属性
cmd.CommandText = "UPDATE tb_command SET 奖金 = 50 WHERE 性别='女'"; //设置CommandText属性,以及SQL语句
cmd.CommandType = CommandType.Text; //SQL文本命令
int i = Convert.ToInt32(cmd.ExecuteNonQuery()); //使用ExecuteNonQuery方法执行SQL语句
label3.Text = "数据表中共有:" + i.ToString() + "名女员工获得奖金";
}
ExecuteReader方法
SqlConnection conn; //声明一个SqlConnection变量
private void button1_Click(object sender, EventArgs e)
{
conn = new SqlConnection("server=.;database=Test;uid=sa;pwd=123"); //实例化SqlConnection变量
conn.Open(); //打开连接
SqlCommand cmd = new SqlCommand(); //创建一个SqlCommand对象
cmd.Connection = conn; //设置Connection属性
cmd.CommandText = "select * from tb_command"; //设置CommandText属性,以及SQL语句
cmd.CommandType = CommandType.Text; //SQL文本命令
SqlDataReader sdr = cmd.ExecuteReader(); //使用ExecuteReader方法实例化一个SqlDataReader对象
while (sdr.Read())
{
listView1.Items.Add(sdr[1].ToString()); //将内容添加到listView1控件中
}
conn.Dispose(); //释放链接
button1.Enabled = false; //禁止按钮
}
ExecuteScalar方法