sqlhelper简单小结

  微软的sqlhelper是个不错的助手类,不过感觉用起来好象不大美观察,下面小结通常用法之


  private const string PARM_TITLE_NAME = "@TitleName";
    private const string SQL_INSERT_TITLE = "INSERT INTO VoteTitle  values(@TitleName,'false')";
   public void AddTitle(string titlename)
    {
        StringBuilder strSQL = new StringBuilder();
        SqlCommand cmd = new SqlCommand();
        // 获取缓存的参数列表
        SqlParameter parm = new SqlParameter(PARM_TITLE_NAME, SqlDbType.NVarChar, 30);
        // 设置参数的值
        parm.Value = titlename;
        //将参数添加到SQL命令中
        cmd.Parameters.Add(parm);

        // 创建连接字符串
        using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionStringLocalTransaction))
        {
            // 添加SQL语句
            strSQL.Append(SQL_INSERT_TITLE);
            conn.Open();
            //设置SqlCommand的属性
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = strSQL.ToString();
            //执行添加语句
            cmd.ExecuteNonQuery();
            //清空参数列表
            cmd.Parameters.Clear(); 
}

  如果是sqldatareader()的话,可以这样
    private const string SQL=“select * from title where titlanem ................";
       public bool IsEffect(string IpAddress,int itemID)
    {
        bool result;
        //创建参数
        SqlParameter[] parms = new SqlParameter[]{new SqlParameter(PARM_ITEM_ID, SqlDbType.Int),
         new SqlParameter(PARM_IP_ADDRESS, SqlDbType.NVarChar, 30)};
        // 设置参数的值
        parms[0].Value = itemID;
        parms[1].Value = IpAddress;

        //执行查询
        using (SqlDataReader rdr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL, parms))
        {
            if (rdr.Read())
                result= false;
            else
                result= true;
        }
        return result;

    }

你可能感兴趣的:(help)