简体   繁体   English

选择语句不适用于C#

[英]Select statement doesn't work on C#

I am trying to get data from local database using this code: 我正在尝试使用以下代码从本地数据库获取数据:

SqlConnection conn = new SqlConnection(@"Data Source = .\SQLEXPRESS; Initial Catalog = serin; Integrated Security = True");
conn.Open();

string query = "SELECT UserPassword FROM UserList WHERE UserName = @UserName";

SqlCommand cmd = new SqlCommand(query, conn);
//SqlParameter param = new SqlParameter("@UserName", SqlDbType.VarChar, txt_UserName.TextLength);
//param.Value = txt_UserName.Text;

//cmd.Parameters.Add(param);
cmd.Parameters.AddWithValue("@UserName", "aliserin");

When I try in this way, it works. 当我以这种方式尝试时,它会起作用。 But when I try to take input from a textbox, it returns NULL. 但是,当我尝试从文本框中获取输入时,它将返回NULL。 I have tried as commented lines, but they also didn't work. 我已经尝试过作为注释行,但是它们也没有用。 I thought maybe it is about type but it doesn't look so. 我以为也许与类型有关,但事实并非如此。

Any help will be appreciated. 任何帮助将不胜感激。

I'm using Visual Studio 2017 and SQL Server 2017. 我正在使用Visual Studio 2017和SQL Server 2017。

Change this line 更改此行

cmd.Parameters.AddWithValue("@UserName", "aliserin");

to this 对此

cmd.Parameters.AddWithValue("@UserName", txt_UserName.Text);

NOTE: Can we stop using AddWithValue() already? 注意: 我们可以停止使用AddWithValue()吗? thanks to @marc_s 感谢@marc_s

don't use a parameter name by the same name as the column... I have historically seen this as a confusion as it sees both a column as the same and uses the column, not the parameter. 不要使用与列相同名称的参数名称...历史上,我一直认为这是一种混淆,因为它将两个列视为相同,并且使用列而不是参数。 Try 尝试

string query = "SELECT UserPassword FROM UserList WHERE UserName = @parmUserName";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@parmUserName", txt_UserName.Text );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM