[英]Unable to insert into sql server in windows authentication
private DateTime currentDate;
private string strInsert;
private SqlCommand sqlCmd;
private SqlConnection hookUp;
protected void EnterData(object sender, EventArgs e)
{
currentDate = DateTime.Now;
hookUp = new SqlConnection("Server=DESKTOP-BDL7T9A;Database=Vote;"
+ "Integrated Security=True;");
strInsert = " INSERT INTO Supporters (LastName,FirstName,";
strInsert += "E-mail,Donation,DateLastContact)VALUES";
strInsert += "(@LName,@FName,@Em,@Donate,@NowDate)";
sqlCmd = new SqlCommand(strInsert, hookUp);
sqlCmd.Parameters.AddWithValue("@LName",LName.Text);
sqlCmd.Parameters.AddWithValue("@FName",FName.Text);
sqlCmd.Parameters.AddWithValue("@Em",Em.Text);
sqlCmd.Parameters.AddWithValue("@Donate",Donate.Text);
sqlCmd.Parameters.AddWithValue("@NowDate",currentDate);
hookUp.Open();
sqlCmd.ExecuteNonQuery();
hookUp.Close();
Lbl1.Text = "Data has been sent";
}
I tried in windows authentication mode. 我在Windows身份验证模式下尝试过。 When I run this code with sqlDatabase server it displays error when I try to submit:
当我使用sqlDatabase服务器运行此代码时,在尝试提交时显示错误:
Incorrect syntax near '-'
'-'附近的语法不正确
when I run this program and input the data at the time of database connection it displays same error. 当我运行该程序并在数据库连接时输入数据时,它显示相同的错误。
You need to use square brackets (delimited identifier) for field names with -
: 对于带有
-
字段名称,您需要使用方括号(定界标识符)
strInsert += "[E-mail],Donation,DateLastContact)VALUES";
Further reading: MSDN Database Identifiers . 进一步阅读:MSDN 数据库标识符 。
You can find there rules for regular identifiers: 您可以在此处找到常规标识符的规则:
- Embedded spaces or special characters are not allowed.
不允许使用空格或特殊字符。
When identifiers are used in Transact-SQL statements, the identifiers that do not comply with these rules must be delimited by double quotation marks or brackets. 在Transact-SQL语句中使用标识符时,不符合这些规则的标识符必须用双引号或括号定界。
Note also that you can use verbatim string to span string literal for several lines of code: 还要注意,您可以使用逐字字符串将字符串文字扩展为几行代码:
strInsert = @"INSERT INTO Supporters
(LastName,FirstName,[E-mail],Donation,DateLastContact)
VALUES (@LName,@FName,@Em,@Donate,@NowDate)";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.