首页 > 解决方案 > 使用 asp.net 时如何检查我的 pin 是否存在于 SQL 数据库中?

问题描述

我正在尝试检查我传递到数据库中的数字是否已经存在。我在我的表单上使用了一个提交按钮,该按钮提交了我的文本框,该文本框的 id="pin" 包含我正在检查的数字。但是,每次我提交它时,它都会说该数字存在,即使它不存在。关于我做错了什么的任何提示?

这是我的 aspx.cs 代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace Test
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string connectionString = @"Data Source=DESKTOP-HOB2BSG\SQLEXPRESS;Initial Catalog=dogdata;Integrated Security=True";

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                sqlCon.Open();

                SqlCommand sqlCmd = new SqlCommand("RetrieveData", sqlCon);
                sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
                sqlCmd.Parameters.AddWithValue("@pin", Int32.Parse(pin.Text.Trim()));

                sqlCmd.ExecuteNonQuery();

                // check if pin exists
                using (SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(*) from dbo.tUser where pin = pin", sqlCon))
                {
                    int userCount = (int)sqlCommand.ExecuteScalar();

                    if (userCount > 0)
                    {
                        Response.Write("<script>alert('Pin Exists!')</script>");
                        new SqlCommand("SELECT IMEI, Sim, DeviceNumber FROM dbo.tUser");
                    }

                    if (userCount < 1)
                    {
                        Response.Write("<script>alert('Pin Doesn't Exist')</script>");
                    }
                }
            }
        }
    }
}

标签: c#asp.netwebforms

解决方案


你的逻辑有点不对劲,试试:

protected void btnSubmit_Click(object sender, EventArgs e)
{
    using (SqlConnection sqlCon = new SqlConnection(connectionString))
    {
        sqlCon.Open();
        SqlCommand sqlCmd = new SqlCommand("SELECT COUNT(*) from dbo.tUser where pin = @pin", sqlCon);
        sqlCmd.CommandType = System.Data.CommandType.Text;
        sqlCmd.Parameters.AddWithValue("@pin", Int32.Parse(pin.Text.Trim()));

        var count = (int)sqlCmd.ExecuteScalar();

        if (count > 0)
        {
            // Pin exists logic
        }
        if (count < 1)
        {
            // Pin doesn't exist logic
        }
    }
}

推荐阅读