对sqlsever数据库的操作流程

下面以以前写的一段代码为例


private void btout_Click(object sender, EventArgs e)
        {
           string source = @"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database1(数据库名称).mdf;Integrated Security=True;User Instance=True";//连接字符串用于连接到本地数据库

记得在解决方案中添加本地数据库 要不然就


          //string st = @"Data Source=HP-HP(主机名);Initial Catalog=(数据库名称);Persist Security Info=True;User ID=(登录名称);Password=(密码)";   用于连接非本地数据库
         

         using(SqlConnection conn = new SqlConnection(source)) //为数据库打开一个连接
          {
              conn.Open();
              using(SqlCommand comm=conn.CreateCommand())//数据库进行操作过程
              {
                  comm.CommandText = "select * from Table1 where name=@Name";//对数据库操作
                  comm.Parameters.Add(new SqlParameter("Name","kk"));//类似以占位符为@Name复制 ,可避免注入漏洞
                  comm.ExecuteNonQuery();//返回执行行数 必要操作
                  using(SqlDataReader read=comm.ExecuteReader())//对用数据库索引出的内容进行读操作
                  {
                      string a=null, b=null;
                      while (read.Read())
                      {
                           a = read.GetString(read.GetOrdinal("name"));
                           b = read.GetString(read.GetOrdinal("age"));
                      }

//--------------------------------------------------------------------------------------------------------------------------------------------
                  SaveFileDialog sfd = new SaveFileDialog();
                  if (sfd.ShowDialog() == DialogResult.OK)
                      {
                         using (FileStream fs = new FileStream(sfd.FileName,FileMode.Open))
                           {   
                              using (StreamWriter sw=new StreamWriter(fs))
                                 {
                                      sw.Write(a);
                                      sw.Write(b);
                                      sw.Close();
                                      fs.Close();
                                     
                                 }
                           }
                       }
                  }
               }
            }
           }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值