[英]Invalid object name 'DB'
I am a beginner and would like to implement basic login page using C#.net - web application. 我是初学者,想使用C#.net-Web应用程序实现基本的登录页面。 I have created database successfully and can test connection worked as well.
我已经成功创建了数据库,并且可以测试连接是否正常工作。 I get the below error message when the control hits ExecuteReader() command.
当控件单击ExecuteReader()命令时,出现以下错误消息。
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
System.Data.dll中发生类型'System.Data.SqlClient.SqlException'的异常,但未在用户代码中处理
Additional information: Invalid object name 'UserDB'.
附加信息:无效的对象名称'UserDB'。
string LoginDbCS =ConfigurationManager.ConnectionStrings["UserDB"].ConnectionString;
string ID = TextBoxUserId.Text;
SqlConnection Conn = new SqlConnection(LoginDbCS);
{
string sCmdStr = "select Password from UserDB where UserID=@ID";
SqlCommand sCmd = new SqlCommand(sCmdStr, Conn);
SqlParameter param = new SqlParameter();
param.ParameterName = "@ID";
param.Value = TextBoxUserId.Text;
sCmd.Parameters.Add(param);
Conn.Open();
SqlDataReader sReader = sCmd.ExecuteReader();
sReader.Read();
if ((string)sReader["Password"]==TextBoxPassword.Text)
{
Label5.Text = "Login Successful";
}
else
{
Label5.Text = "No Records found";
}
sReader.Close();
Conn.Close();
}
} }
Looking forward for suggestions to fix this crash. 期待获得解决此崩溃的建议。
Well, Your question was answered in the comments by sohaiby , but there are some deeper issues with your code, and you should fix those. 好的,您的问题已在sohaiby的注释中得到了回答 ,但是您的代码存在一些更深层次的问题,因此您应该解决这些问题。
I believe that it's easier to learn good coding standards as a beginner then as someone that has experience with bad coding standards, since people often go to what is familiar when thing go bad. 我相信,作为一个初学者,要学习良好的编码标准要比有一个糟糕的编码标准的人学习起来容易,因为当事情变糟时,人们通常会去熟悉的事物。
So, here are some bad practices that you should replace ASAP: 因此,这是您应尽快替换的一些不良做法:
string sCmdStr = "select * from UserDB where UserID=@ID AND Password = @Password";
ExecuteScalar
to get a single value from the database. ExecuteScalar
从数据库中获取单个值。 ExecuteScalar
will return null. ExecuteScalar
将返回null。 read how to handle this here. SqlConnection
in your case) without a Using
statement. SqlConnection
)而不Using
语句。 I hope this will help you learn better coding standards and improve your coding skills. 我希望这将帮助您学习更好的编码标准并提高您的编码技能。
Happy programming! 编程愉快!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.