我试图将文本框中的数据插入到我的数据库中,这给我一个例外。
异常详细信息:System.Data.SqlClient.SqlException:'test'附近的语法不正确。
在我提交代码之前的一些细节: 我的数据库叫做:电影 我的表数据称为:用户 我有一些列,如:“FirstName”,“LastName”等...
protected void Register_Click(object sender,EventArgs e) { SqlConnection connection = new SqlConnection(“Data Source = MICROSOF-58B8A5 \ SQL_SERVER_R2; Initial Catalog = Movie; Integrated Security = True”);
connection.Open();
//FirstName***********
string firstName = FirstNameTextBox.Text;
string sqlquery = ("INSERT INTO [Users] (FirstName) VALUES (' " +FirstNameTextBox.Text + " ' ");
SqlCommand command = new SqlCommand(sqlquery , connection);
command.Parameters.AddWithValue("FirstName", firstName);
//LastName************
string lastName = LastNameTextBox.Text;
sqlquery = ("INSERT INTO [Users] (LastName) VALUES (' " + LastNameTextBox.Text+ " ' ");
command.Parameters.AddWithValue("LastName", lastName);
//Username*************
string username = UsernameTextBox.Text;
sqlquery = ("INSERT INTO [Users] (Username) VALUES (' " + UsernameTextBox.Text+ " ' ");
command.Parameters.AddWithValue("UserName", username);
//Password*************
string password = PasswordTextBox.Text;
sqlquery = ("INSERT INTO [Users] (Password) VALUES (' " + PasswordTextBox.Text + " ' ");
command.Parameters.AddWithValue("Password", password);
if (PasswordTextBox.Text == ReTypePassword.Text)
{
command.ExecuteNonQuery();
}
else
{
ErrorLabel.Text = "Sorry, You didnt typed your password correctly. Please type again.";
}
connection.Close();
}
答案 0 :(得分:5)
使用一个查询并使用@ParamName
:
string sqlquery = "INSERT INTO [Users] (FirstName,LastName,UserName,Password) VALUES (@FirstName,@LastName,@UserName,@Password)";
SqlCommand command = new SqlCommand(sqlquery , connection);
//FirstName***********
string firstName = FirstNameTextBox.Text;
command.Parameters.AddWithValue("FirstName", firstName);
//LastName************
string lastName = LastNameTextBox.Text;
command.Parameters.AddWithValue("LastName", lastName);
//Username*************
string username = UsernameTextBox.Text;
command.Parameters.AddWithValue("UserName", username);
//Password*************
string password = PasswordTextBox.Text;
command.Parameters.AddWithValue("Password", password);
...........
答案 1 :(得分:0)
问题似乎是您正在创建一个奇怪的SQL指令。它的真正价值在于 INSERT INTO [Users](FirstName)VALUES('(theValue)') 而且你没有添加其余的值(姓氏等)。其余代码什么都不做,因为查询不包含其余参数。
答案 2 :(得分:0)
也许这段代码更短:
sqlcommand command=new sqlcommand("insert into[Users](FirstName,LastName,UserName,Password) values('"+FirstNameTextBox.Text+"','"+LastNameTextBox.Text+"','"+UsernameTextBox.Text+"','"+PasswordTextBox.Text+"')",connection);
command.ExecuteNonQuery();
答案 3 :(得分:0)
也添加以下内容:
string sqlquery = "INSERT INTO [Users] (FirstName,LastName,Username,Password) VALUES ( " +FirstNameTextBox.Text + " ,";
sqlquery += LastNameTextBox.Text+ ",";
sqlquery += UsernameTextBox.Text+ ",";
sqlquery += PasswordTextBox.Text + " )";
SqlCommand command = new SqlCommand(sqlquery , connection);