gpt4 book ai didi

c# - C# 链接到 SQL Server Express 的错误输出

转载 作者:太空宇宙 更新时间:2023-11-03 15:10:00 27 4
gpt4 key购买 nike

下面是我按下按钮后得到的输出,尽管 EmployeeNumberDOB 确实存在于我的 SQL Server 数据库中。

我已经尝试了很多次,但无法找出导致错误输出的问题。

Output from C#

感谢您的帮助!

C#代码:

private void btn_Click(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["FirstConnection"].ConnectionString;

SqlConnection con = new SqlConnection(constring);

SqlCommand cmd = new SqlCommand("spEmployeeC", con);
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.AddWithValue("@Employee", txtEmployee.Text);
cmd.Parameters.AddWithValue("@DOB", txtPassword.Text);

//cmd.IsValid

con.Open();

cmd.ExecuteNonQuery();

if (txtEmployee.Text == "@Employee" && txtPassword.Text == "@DOB")
{
MessageBox.Show("Welcome " + txtEmployee.Text);
}
else
{
MessageBox.Show("The Username or Password you entered is incorrect. Please try again");
}
}

SQL Server 存储过程代码:

CREATE PROCEDURE spEmployeeC
@Employee INT,
@DOB DATE
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Employee_check INT;
DECLARE @Password_check DATE;

SELECT *
FROM Employee_Table
WHERE [EMPLOYEE_NUM] = @Employee AND [DOB] = @DOB
END

最佳答案

像这样会更好:

    protected void btn_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtEmployee.Text))
{
MessageBox.Show("You must supply an Employee Number");
return;
}

if (string.IsNullOrEmpty(txtPassword.Text))
{
MessageBox.Show("You must supply a Password");
return;
}

if (IsAuthenticated())
{
MessageBox.Show("Welcome " + txtEmployee.Text);
}
else
{
MessageBox.Show("The Username or Password you entered is incorrect. Please try again");
};
}

private bool IsAuthenticated()
{
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("spValidateCredentials", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Employee", SqlDbType.Int).Value = txtEmployee.Text;
cmd.Parameters.Add("@DOB", SqlDbType.Date).Value = DateTime.Parse(txtPassword.Text);
conn.Open();
return ((int)cmd.ExecuteScalar() > 0);
}
}

也可以更改存储过程以返回记录数:

CREATE PROCEDURE [dbo].[spValidateCredentials]
@Employee INT,
@DOB DATE
AS
BEGIN
SELECT COUNT(*)
FROM Employee_Table
WHERE EMPLOYEE_NUM=@Employee
AND DOB=@DOB
END

关于c# - C# 链接到 SQL Server Express 的错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41656504/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com