制作与后台SQL server数据库连接的登入界面(详解)

制作与后台SQL server数据库连接的登入界面(详解)

  命名空间: System.Data.SqlClient 

  程序集: System.Data(在 System.Data.dll 中) 

  C#: 

  public sealed class SqlCommand : DbCommand, ICloneable 

  当创建 SqlCommand 的实例时,读/写属性将被设置为它们的初始值。 

  您可以重置 CommandText 属性并重复使用 SqlCommand 对象。但是,在执行新的命令或先前命令之前,必须关闭 SqlDataReader。如果执行 SqlCommand 的方法生成 SqlException,那么当严重级别小于等于 19 时,SqlConnection 将仍保持打开状态。当严重级别大于等于 20 时,服务器通常会关闭 SqlConnection。但是,用户可以重新打开连接并继续。 

编辑本段Sqlcommand实例

1

  private static void ReadOrderData(string connectionString) 

  { 

  string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;"; 

  using (SqlConnection connection = new SqlConnection( connectionString)) 

  { 

  SqlCommand command = new SqlCommand( queryString, connection); connection.Open(); 

  SqlDataReader reader = command.ExecuteReader(); 

  try 

  { 

  while (reader.Read()) 

  { 

  Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1])); 

  } 

  } 

  finally 

  { 

  // Always call Close when done reading. reader.Close(); 

  } 

  } 

  } 

2

  string str = "server='(local)';database='mytable';uid='sa';pwd='sa'"; 

  SqlConnection con = new SqlConnection(str); //创建连接对象 

  con.Open(); //打开连接 

  其中,str是数据连接字串,用来初始化Connection对象,说明如何连接数据库,当数据库连接完毕后,可以使用Open方法打开数据连接。完成数据库连接后,需创建一个新的Command对象,示例代码如下所示。 

  SqlCommand cmd = new SqlCommand("insert into mynews value ('插入一条新数据')", con); 

  Command对象的构造函数的参数有两个,一个是需要执行的SQL语句,另一个是数据库连接对象。创建Command对象后,就可以执行SQL命令,执行后完成并关闭数据连接,示例代码如下所示。 

  cmd.ExecuteNonQuery(); //执行SQL命令 

  con.Close(); //关闭连接 

  3 SqlCommand对象有三个方法; 

  1.ExecuteNonQuery();它的返回值类型为int型。多用于执行增加,删除,修改数据。返回受影响的行数。 

  2.ExecuteReader();它的返回类型为SqlDataReader。此方法用于用户进行的查询操作。使用SqlDataReader对象的Read();方法进行逐行读取。 

  例如: 

  SqlCommand comm =new SqlCommand("select * from CGSZ where cid="+id,conn); 

  SqlDataReader reder=comm.ExecuteReader(); 

  while(reder.Read()) 

  { 

  //读出内容列 

  string str=reder["cname"].ToString(); 

  //读取分类列 

  string str1=reder["ckind"].ToString(); 

  //分别为文本框加载数据 

  this.txtContent.Text = str; 

  this.txtClass.Text = str1; 

  } 

  其中的读取数据列的时候。除了使用reder["列名"].ToString();还可以使用reder[索引].ToSting();<注意:这里的索引指的是数据库中列的索引。从0开始。> 

  3.3.ExecuteScaler();它的返回值类型多位int类型。它返回的多为执行select查询。得到的返回结果为一个值的情况,比如使用count函数求表中记录个数或者使用sum函数求和等。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值