带参数的查询怎么写?

陶新新同学问起带参数的ADO.NET怎么写,为什么要带参数?

带参数的一个重要作用是安全,如防止SQL注入;再就是代码上更加规范,逻辑上更加清晰……

using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;

using  System.Data;
using  System.Data.Common;
using  System.Data.SqlClient;


///使用带参数的查询,基本方法如下:
///写SQL语句,参数用@引导;有几个@参数就有几个 SqlParameter 对象;将所有的SqlParameter对象添加到SqlCommand对象
的Parameters集合。
namespace  snippetConsole
{
    
class  Program
    {
        
static   void  Main( string [] args)
        {
            
string  connect  =   " Data Source=.\\sqlexpress; Initial Catalog=Northwind ; Integrated Security = true; " ;
            
string  select  =   " select CustomerID,City from Customers where CustomerID =@customer_id and City=@city  " ;
            
//  ('ANTON','AROUT','BERGS','BLAUS')";London    Aachen    Nantes    London

            SqlConnection cn 
=   new  SqlConnection(connect);
            SqlCommand cmd 
=   new  SqlCommand(select, cn);
            SqlParameter paramCustID 
=   new  SqlParameter( " @customer_id " " ALFKI " );    //  此处ALFKI可以是外部的文本框等
            SqlParameter paramCity  =   new  SqlParameter( " @city " " Berlin " );                    // 此处的Berlin可以是外部文本框控件获得数据
            cmd.Parameters.Add(paramCustID);
            cmd.Parameters.Add(paramCity);

            cn.Open();
            SqlDataReader drCustomer 
=  cmd.ExecuteReader();
            
if  (drCustomer.HasRows)
            {
                
while  (drCustomer.Read())
                {
                    Console.WriteLine(
" CustomerID:{0}\tCompanyName:{1} " ,
                    drCustomer.GetString(
0 ), drCustomer.GetString( 1 ));
                }
            }

            cn.Close();
            Console.ReadKey();
        }
    }
}

 

转载于:https://www.cnblogs.com/flaaash/archive/2011/03/22/1991585.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值