C#asp.net sql 增删改查代码

string MyConn="server=127.0.0.1;uid=user;pwd=123456;database=Northwind;Trusted_Connection=no";//定义数据库连接参数
SqlConnection MyConnection=new SqlConnection(MyConn);//定义一个数据连接实例
SqlCommand MyCommand=new SqlCommand("SELECT CategoryID, CategoryName, Description FROM Categories",MyConnection); //定义一个数据库操作指令
SqlDataAdapter SelectAdapter=new SqlDataAdapter();//定义一个数据适配器
SelectAdapter.SelectCommand=MyCommand;//定义数据适配器的操作指令
DataSet MyDataSet=new DataSet();//定义一个数据集
MyConnection.Open();//打开数据库连接
SelectAdapter.SelectCommand.ExecuteNonQuery();//执行数据库查询指令
MyConnection.Close();//关闭数据库
SelectAdapter.Fill(MyDataSet);//填充数据集
DataGrid1.DataSource=MyDataSet;
DataGrid1.DataBind();//将数据表格用数据集中的数据填充

第二、添加数据
string MyConn="server=127.0.0.1;uid=user;pwd=123456;database=Northwind;Trusted_Connection=no";
SqlConnection MyConnection=new SqlConnection(MyConn);
string MyInsert="insert into Categories(CategoryName, Description)values('"+Convert.ToString(TextBox2.Text)+"','"+Convert.ToString(TextBox3.Text)+"')";
SqlCommand MyCommand=new SqlCommand(MyInsert,MyConnection);
try//异常处理
{
MyConnection.Open();
MyCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch(Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}

第三、修改数据
string categoryName=TextBox2.Text;
string categoryDescription=TextBox3.Text;
string MyConn="server=127.0.0.1;uid=user;pwd=123456;database=Northwind;Trusted_Connection=no";
SqlConnection MyConnection=new SqlConnection(MyConn);
string MyUpdate="Update Categories set CategoryName='"+categoryName+"',Description='"+categoryDescription+"' where CategoryID="+TextBox1.Text;
SqlCommand MyCommand=new SqlCommand(MyUpdate,MyConnection);
try
{
MyConnection.Open();
MyCommand.ExecuteNonQuery();
MyConnection.Close();
TextBox1.Text="";
}
catch(Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}

第四、删除数据
string MyConn="server=127.0.0.1;uid=user;pwd=123456;database=Northwind;Trusted_Connection=no";
SqlConnection MyConnection=new SqlConnection(MyConn);
string MyDelete="Delete from Categories where CategoryID="+TextBox1.Text;
SqlCommand MyCommand=new SqlCommand(MyDelete,MyConnection);
try
{
MyConnection.Open();
MyCommand.ExecuteNonQuery();
MyConnection.Close();
TextBox1.Text="";
}
catch(Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}


webform