学习笔记(ADO.Net中SqlConnection、Sqlcommand的应用)

一、思维导图

学习笔记(ADO.Net中SqlConnection、Sqlcommand的应用)

 

学习笔记(ADO.Net中SqlConnection、Sqlcommand的应用)

二、知识点

  1. 开发界面代码开头需添加引用using System.Data.SqlClient,包含访问SQL SERVER所需的各类对象;
  2. 连接,open()打开连接,close()关闭连接
  • 直接声明并实例化SQL连接,在在字符串变量中,描述连接字符串所需的服务器地址、数据库名称、集成安全性,用sqlConnection.State.ToString()显示当前的连接状态;
  • 先声明并实例化SQL连接,然后利用SQL连接字符串构造器分别将各控件的内容赋予SQL连接字符串构造器的相应属性,即数据源、初始化条目(数据库)、集成安全性(是否windows验证);
  • 也可以利用配置文件实现更方便的连接,需要先添加包含访问配置文件所需的配置管理器,即添加引用System.Configuration,接着配置管理器从配置文件读取连接字符串,并将之赋予SQL连接的连接字符串属性;
  • 还可以对连接字符串实现加密,即保存,通过.ConnectionStrings.ConnectionStrings.Add(connectionStringSettings)来实现新连接字符串的写入,然后configuration.ConnectionStrings.SectionInformation.ProtectSection(null)对连接字符串进行加密;

     3.命令

  • 直接声明并实例化SQL命令,SQL命令的命令文本由字符串拼接而成,不含参数,然后调用SQL命令的方法ExecuteScalar来执行命令,返回标量结果,执行标量的返回结果类型为object,可通过强制类型转换,转为整型;
  • 第二种是命令文本包含参数,SQL参数有两种用法,用法1是声明并实例化参数,然后设置参数的各种属性,最后向SQL命令的参数集合添加SQL参数;用法2是直接调用方法AddWithValue向SQL命令的参数集合添加参数的名称、值,但需注意的是由于HASHBYTES函数的参数为NVARCHAR,则SQL参数类型自动设为NVARCHAR,需手动转换成VARCHAR,使用SQL参数可以避免注入式攻击,安全性较高;
  • 也可以调用SQL连接的方法CreateCommand来创建SQL命令,然后调用SQL命令的方法ExecuteNonQuery来执行命令,向数据库写入数据,并返回受影响行数;
  • 执行命令后可以通过try....catch...捕捉SQL异常;
  • 还可以指定命令文本为存储过程名称,若SQL参数被用作某存储过程的输入参数,则使用存储过程定义的参数类型作为SQL参数的类型;

三、范例

  1. 连接数据库

          配置文件:

<configuration>
  <connectionStrings>
    <add name="ConnectionSql" 
         connectionString="Server=(local);Database=EduBaseDemo;Integrated Security=sspi"
         providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>

public frm_Connection()
        {

if (ConfigurationManager.ConnectionStrings["ConnectionSql"] != null)                                                          
            {
                SqlConnectionStringBuilder sqlConnectionStringBuilder =  new SqlConnectionStringBuilder();                     
                sqlConnectionStringBuilder.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionSql"].ConnectionString;   
                this.txb_Server.Text = sqlConnectionStringBuilder.DataSource;                                                
                this.txb_Database.Text = sqlConnectionStringBuilder.InitialCatalog;
                this.ckb_IsWindowsAuthentication.Checked = sqlConnectionStringBuilder.IntegratedSecurity;
            }
        }

 private void btn_Connect_Click(object sender, EventArgs e)
        {
            SqlConnection sqlConnection = new SqlConnection();                                                                  
            sqlConnection.ConnectionString =
                ConfigurationManager.ConnectionStrings["ConnectionSql"].ConnectionString;                                                 
            sqlConnection.Open();                                                                                             
            MessageBox.Show                                                                                                    
                ("连接状态:" + sqlConnection.State.ToString()                                                               );
            sqlConnection.Close();                                                                                              
        }

     2.账号登录

 SqlConnection sqlConnection = new SqlConnection();                                          
            sqlConnection.ConnectionString =  "Server=(local);Database=EduBaseDemo;Integrated Security=sspi";                        
            SqlCommand sqlCommand = sqlConnection.CreateCommand();                                  
            sqlCommand.CommandText =
                "SELECT COUNT(1) FROM tb_User WHERE [email protected] AND Password=HASHBYTES('MD5',@Password);"

sqlCommand.Parameters.AddWithValue("@No", this.txb_UserNo.Text.Trim());     

sqlCommand.Parameters.AddWithValue("@Password", this.txb_Password.Text.Trim());             
sqlCommand.Parameters["@Password"].SqlDbType = SqlDbType.VarChar;   

sqlConnection.Open();                                                                       
int rowCount = (int)sqlCommand.ExecuteScalar();                                             
sqlConnection.Close();                                                                     
if (rowCount == 1)                                                                         
  {
       MessageBox.Show("登录成功。");                                                         
  }
 else                                                                                        
  {
     MessageBox.Show("用户号/密码有误,请重新输入!");                                     
     this.txb_Password.Focus();                                                              
     this.txb_Password.SelectAll();                                                         
 }