您好,我制作了manullay创建的文本框,然后将其用于创建新用户。我使用SQL SERVER 2005作为后端和Visual Server 2008作为前端。我有这个LoginAccount表,它存储了创建的新用户的详细信息。当我点击该按钮(在我所编写的代码创建通过SQL插入一个新的用户),通过C#将值插入到SQL表中时出现异常
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” 这个错误我得到的第一个catch
和
未将对象引用设置为对象的实例。 这是最后一次。
但更主要的是,我能够插入用户名和密码进入登录账号表!!!!!!!即当我看到表格内容时,我可以看到在该表格中创建的新用户。 另一件事是完美前一次,但不执行该代码现在:( 请任何人都可以告诉我,我要去哪里错了 我是新来的C#与SQL ...
谢谢..该死的我一遍又一遍地查看了整个代码,但没有发现这样愚蠢的错误...... – 2010-07-23 09:36:13
没问题......正如cryss说的,虽然这个代码还有其他问题。使用sql参数而不是构建sql字符串。在你需要它们之前不要创建命令对象。使用子句包装连接和命令对象。我不确定Server.Transfer是否会杀死当前线程,但如果它确实存在,那么sql连接永远不会关闭。 (使用会解决这个问题)。 享受 – 2010-07-23 12:53:27