您的位置:首页 > 数据库

命令对象SqlCommand(四)执行语句

2012-07-18 00:46 267 查看
View Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace CommandNonQuery
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection(@"Data Source=.;Initial Catalog=Northwind;Integrated Security=True");
string sqlqry = @"select count(*) from employees";
string sqlins=@"insert into employees(firstname,lastname) values('tan','ding')";
string sqldel = @"delete from employees where firstname='tan' and lastname='ding'";

SqlCommand cmdqry = new SqlCommand(sqlqry, conn);
SqlCommand cmdnon = new SqlCommand(sqlins, conn);

try
{
conn.Open();
Console.WriteLine("Before Insert:Number of employees {0}\n", cmdqry.ExecuteScalar());

Console.WriteLine("Executing statement {0}", cmdnon.CommandText);
cmdnon.ExecuteNonQuery();
Console.WriteLine("After Insert:Number of employees {0}\n", cmdqry.ExecuteScalar());

cmdnon.CommandText = sqldel;
Console.WriteLine("Executing statement {0}", cmdnon.CommandText);
cmdnon.ExecuteNonQuery();
Console.WriteLine("After Delete:Number of employees {0}\n", cmdqry.ExecuteScalar());
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
conn.Close();
Console.WriteLine("Connection closed.");
}
Console.ReadKey();
}
}
}




示例说明:3条SQL语句存放在3个字符串变量中,首先是查询行,然后插入行,最后初始化其CommandText属性,设置删除语句,删除插入的行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: