命令对象SqlCommand(四)执行语句
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属性,设置删除语句,删除插入的行。