Executing SQL statements using SqlCommand

Source: Internet
Author: User

stringsConnectionString = @"server=(local)\SQLEXPRESS;database=Forum;Trusted_Connection=True";

using (SqlConnection conn = new SqlConnection(sConnectionString)) {      conn.Open();      using (SqlCommand cmd = new SqlCommand())      {          // 绑定有效的数据库连接          cmd.Connection = conn;          // 定义操作1的SQL语句          cmd.CommandText = "Insert into tbClass (ClassName) values (‘网页设计‘)" ;          // 完成操作1并输出相应的记录数          Response.Write( string .Format( "在tbClass中插入了{0}条记录<br>" , cmd.ExecuteNonQuery()));          // 定义操作2的SQL语句          cmd.CommandText = "Select ClassID from tbClass where ClassName=‘网页设计‘" ;          // 完成操作2          string sClassID = cmd.ExecuteScalar().ToString();          // 输出操作2的结果          Response.Write( string .Format( "ClassID为{0}<br>" , sClassID));          // 定义操作3的SQL语句          cmd.CommandText = string .Format( "Insert into tbBoard (BoardName,BoardClassID) values (‘PHOTOSHOP‘,‘{0}‘);Insert into tbBoard (BoardName,BoardClassID) values (‘FIREWORKS‘,‘{0}‘)" , sClassID);          // 完成操作3并输出相应的记录数          Response.Write( string .Format( "在tbBoard中插入了{0}条记录<br>" , cmd.ExecuteNonQuery()));          // 定义操作4的SQL语句          cmd.CommandText = "Update tbBoard set BoardName=‘PS技术‘ where BoardName=‘PHOTOSHOP‘" ;          // 完成操作4并输出相应的记录数          Response.Write( string .Format( "在tbBoard中修改了{0}条记录<br>" , cmd.ExecuteNonQuery()));          // 定义操作5的SQL语句          cmd.CommandText = string .Format( "Delete from tbBoard where BoardClassID=‘{0}‘" , sClassID);          // 完成操作5并输出相应的记录数          Response.Write( string .Format( "在tbBoard中删除了{0}条记录<br>" , cmd.ExecuteNonQuery()));          // 定义操作6的SQL语句          cmd.CommandText = string .Format( "Delete from tbClass where ClassID=‘{0}‘" , sClassID);          // 完成操作6并输出相应的记录数          Response.Write( string .Format( "在tbClass中删除了{0}条记录<br>" , cmd.ExecuteNonQuery()));      } }

Executing SQL statements using SqlCommand

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.