数据类型错误将varchar转换为int失败

时间:2018-10-26 19:09:56

标签: c# asp.net sql-server

我正在存储cookie并尝试在cookie的帮助下在购物车中显示商品,但出现此错误“在将购物车的varchar值'CartPID'转换为数据类型int时转换失败”,单击购物车时按钮。我知道CartPID是varchar,但是我该如何克服这个错误。在index [0] =“ CartPID”处,它持有字符串值,而我需要从One开始的索引上的int值。

 string CookieData = Request.Cookies["CartPID"].Value.Split('=')[1];
        string[] CookieDataArray = CookieData.Split(',');
        if (CookieDataArray.Length > 0)

        {
            h5NoItems.InnerText = "MY CART (" + CookieDataArray.Length + " Items)";//to show total num of items 
            DataTable dt = new DataTable();
            Int64 CartTotal = 0;
            Int64 Total = 0;
            for (int i = 0; i <= CookieDataArray.Length; i++)//this loop will get PID and sizeID
            {
                string PID = CookieDataArray[i].ToString().Split('-')[0];
               // string SizeID = CookieDataArray[i].ToString().Split('-')[1];
                String CS = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
                using (SqlConnection con = new SqlConnection(CS))
                {

                    using (SqlCommand cmd = new SqlCommand("Select * from Products where ID='" + PID+"'", con))

                    {
                        cmd.CommandType = CommandType.Text;
                        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                        {
                            sda.Fill(dt);
                        }

                    }

2 个答案:

答案 0 :(得分:1)

在确保输入安全之前,切勿使用来自客户端的输入。建立此查询时使用SqlParameter,这样就不会促进SQL注入

var query = "Select  * from Products where ID = @id";
using( var command = new SqlCommand(query, con){
    command.Parameters.Add("@id", SqlDbType.Varchar).Value = pid;
    .... 
}

如果PID确实是一个int,请使用类似以下内容的

int pid;
if(int.TryParse(CookieDataArray[i].ToString().Split('-')[0], out pid){
// the sql command goes here SqlDbType.Int this time
}

答案 1 :(得分:0)

using (SqlCommand cmd = new SqlCommand("Select * from Products where ID=" + PID, con))
{
    cmd.CommandType = CommandType.Text;

    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
    {
        sda.Fill(dt);
    }
}

或尝试

using (SqlCommand cmd = new SqlCommand("Select * from Products where ID=@PID", con))
{
    cmd.Parameters.Add("@PID", SqlDbType.Int);
    cmd.Parameters["@PID"].Value = PID;

    cmd.CommandType = CommandType.Text;

    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
    {
        sda.Fill(dt);
    }
}