C# 通过C将值插入SQL表时发生异常
嗨,我让manullay创建了textbox,然后用它创建了一个新用户。我使用SQL SERVER 2005作为后端,使用Visual SERVER 2008作为前端 我有一个LoginAccount表,它存储了新用户创建的详细信息。当我点击我已经编写代码的按钮,通过SQL insert创建一个新用户时C# 通过C将值插入SQL表时发生异常,c#,sql,visual-studio-2008,C#,Sql,Visual Studio 2008,嗨,我让manullay创建了textbox,然后用它创建了一个新用户。我使用SQL SERVER 2005作为后端,使用Visual SERVER 2008作为前端 我有一个LoginAccount表,它存储了新用户创建的详细信息。当我点击我已经编写代码的按钮,通过SQL insert创建一个新用户时 string strConnection = ConfigurationManager.ConnectionStrings"FHDLConnectionString"].ToString()
string strConnection = ConfigurationManager.ConnectionStrings"FHDLConnectionString"].ToString();
SqlConnection sqlConnection = new SqlConnection(strConnection);
string username = TextBox1.Text;
string password = TextBox2.Text;
string confirmpass = TextBox3.Text;
string SQLQuery = "Select username From LoginAccount where '" + username + "'";
string SQLQuery1 = "Insert into LoginAccount values ('" + username + "','" + password + "')";
SqlCommand command = new SqlCommand(SQLQuery, sqlConnection);
SqlCommand command1 = new SqlCommand(SQLQuery1, sqlConnection);
sqlConnection.Open();
string CheckUsername = "";
if (password.ToString() != confirmpass.ToString())
{
Literal1.Text = " Password's does not match ";
}
else
{
try
{
CheckUsername = command.ExecuteScalar().ToString();
}
catch (Exception er)
{
Literal1.Text = " Username already exists ";
}
string insertQuery = "";
try
{
insertQuery = command1.ExecuteScalar().ToString();
Server.Transfer("Login_Created.aspx");
}
catch (Exception er)
{
Literal1.Text = " Could not create the user, Please retry with some other option ";
}
}
sqlConnection.Close();
我得到了这些例外的
在预期条件的上下文中指定的非布尔型表达式,靠近“fhdl”
这是我第一次犯的错误
及
对象引用未设置为对象的实例。
这是我最后一次接球时用的
但最重要的是我能够将用户名和密码插入LoginAccount表中!!!!!!!i、 当我看到表格内容时,我可以看到在该表格中创建的新用户。
另一件事是这段代码以前完美执行过一次,但现在没有:
谁能告诉我哪里出了问题?
我不熟悉使用SQl的C…有三件事:
您的第一个查询没有达到您希望的效果。决议如下:
从“用户名”所在的LoginAccount中选择用户名
您想根据数据库检查用户名
这段代码使您容易受到SQL注入攻击。请参阅,了解如何在C中预防它们
同样,您也不想将密码存储在数据库的clear中。
1-ExecuteScalar表示有一个返回值。插入没有返回值。改用ExecuteOnQuery 2-另外,对于insert语句,指定要插入的字段。在不指定字段的情况下,它试图插入表的前两列,这两列可能不是用户名和密码 插入LoginAccountUserName、密码值 3-您的select语句不正确
从用户名为“”的LoginAccount中选择。。。您缺少字段名。谢谢。。该死的,我一次又一次地查看整个代码,但没有发现这样愚蠢的错误…没问题。。。正如cryss所说,这段代码还有其他问题。使用sql参数而不是生成sql字符串。在需要之前不要创建命令对象。用using子句包装CONNECTION和command对象。我不确定Server.Transfer是否终止当前线程,但如果终止,则sql连接永远不会关闭。使用会解决这个问题。享受