c# - 使用 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>");
}
}
}
}
}
}
解决方案
你的逻辑有点不对劲,试试:
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
}
}
}
推荐阅读
- ios - Ant Media Server 的 iOS 框架不被 App Store 接受?
- bash - 使用正则表达式进行密码验证在我的 shell 脚本中不起作用
- javascript - 为什么在分配之前,console.log中的js对象不为空?
- python - 从 PostgreSQL 函数运行 Python 脚本
- c++ - 如何使用迭代器设计模式对二叉树进行 BFS 遍历
- c# - 如何在 C# 中处理取决于单击的行和列的 WPF 数据网格单元格上的鼠标单击
- javascript - Paho MQTT Javascript 客户端版本 1.1.0 连接问题
- html - 为什么不“" 通过 jQuery 附加它时成为父元素?
- unit-testing - 使用 javax.ws.rs.client 对 inputStream 进行 Java 编写测试
- vba - 使用 Internet Explorer 发表 YouTube 评论