5

我有一个页面,您填写一些信息,并根据该信息向数据库中插入一个新行。这是填写的表格的屏幕截图:

在此处输入图像描述

这是我单击提交按钮时插入数据库的代码:

 protected void CreateCourseButton_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection();
    con.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=University;Integrated Security=True;Pooling=False";

    string query1 = "insert into Courses(CRN,CourseName,StudyLevel,Capacity,Instructor,Credits,Prerequisite) values ("
        + courseID.Text + "," + courseName.Text + "," + studyLevel.SelectedValue + "," + capacity.Text + "," + "Admin," + credits.Text + "," + prereq.Text + ")";



    SqlCommand cmd1 = new SqlCommand(query1, con);
    con.Open();
    cmd1.ExecuteNonQuery();
    con.Close();
}

问题是,单击提交时出现以下错误:

Server Error in '/Bannerweb' Application.

Incorrect syntax near the keyword 'to'.

Description: An unhandled exception occurred during the execution of the current web     
request. Please review the stack trace for more information about the error and where   
it originated in the code. 

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the   
keyword 'to'.

Source Error: 


Line 32:         SqlCommand cmd1 = new SqlCommand(query1, con);
Line 33:         con.Open();
Line 34:         cmd1.ExecuteNonQuery();
Line 35:         con.Close();
Line 36:     }

Source File: c:\Banner\Bannerweb\Pages\CreateCourse.aspx.cs    Line: 34 

Stack Trace: 


[SqlException (0x80131904): Incorrect syntax near the keyword 'to'.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean     
breakConnection) +2084930
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean    
breakConnection) +5084668
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +234
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler,   
SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject  
stateObj) +2275
   System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean 
async) +228
   System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result,     
String methodName, Boolean sendToPipe) +326
   System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +137
   CreateCourse.CreateCourseButton_Click(Object sender, EventArgs e) in  
c:\Banner\Bannerweb\Pages\CreateCourse.aspx.cs:34
  System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112

第 34 行是:

cmd1.ExecuteNonQuery();

谁能帮我解决这个错误?

谢谢

4

7 回答 7

6

发生此错误是因为您在插入的值之间缺少 ''。无论如何,最好的方法是使用Parameters这样的集合:

string query1 = "insert into Courses(CRN,CourseName,StudyLevel,Capacity,Instructor,Credits,Prerequisite) values (@crn, @cursename, @studylevel, @capacity, @instructor, @credits, @prerequesite)";

SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.Parameters.AddWithValue("@crn", courseID.Text);
//add the rest

con.Open();
cmd1.ExecuteNonQuery();
con.Close();
于 2013-05-14T11:01:04.217 回答
3

看起来你需要在Course Name. 也使用SQL parameterized queries这样你就不容易受到SQL Injection.

'" + courseName.Text + "'

将评估为:

'Intro to comp'

http://johnhforrest.com/2010/10/parameterized-sql-queries-in-c/

于 2013-05-14T10:58:44.040 回答
1

'您必须像这样在更新您的 sql 查询中传递所有控件的值:

   string query1 = "insert into 
Courses(CRN,CourseName,StudyLevel,Capacity,Instructor,Credits,Prerequisite) values ("+
"'" + courseID.Text + "'" + "," + "'" + courseName.Text + "'" + "," + 
"'" + studyLevel.SelectedValue + "'" + "," + "'" + capacity.Text + "'" +
"," + "'Admin'," + "'" + credits.Text + "'" + "," +  "'"+prereq.Text +"'" + ")";

//返回查询影响的行数

int a= cmd1.ExecuteNonQuery();
if(a>0)
{
//inserted
}
else
{
//not inserted
}

在这里查看更多详细信息。

于 2013-05-14T11:00:55.717 回答
1

此错误可能来自Course name字段,其中值中有空格。要仅修复它,您可以将 的值包装TextBoxes'char 中。

但是,这是一个巨大的安全漏洞。如今,您必须使用参数,例如您的插入必须如下所示:

SqlConnection con = new SqlConnection();
con.ConnectionString = "...";

string query1 = "insert into Courses(CRN,CourseName,StudyLevel,Capacity,Instructor,Credits,Prerequisite)"+
    " values (@CRN, @CourseName, ...)";



SqlCommand cmd1 = new SqlCommand(query1, con);

// Insert parameters
cmd1.Parameters.AddWithValue("@CRN",courseID.Text);
...

con.Open();
cmd1.ExecuteNonQuery();
con.Close();

您必须使用参数来保护自己免受 SQL 注入攻击。

于 2013-05-14T11:03:27.573 回答
1

尝试这个

string query1 = "insert into Courses(CRN,CourseName,StudyLevel,Capacity,Instructor,Credits,Prerequisite) 
        values ('"+ courseID.Text +"','"+ courseName.Text + "','" + studyLevel.SelectedValue +"', '" + capacity.Text +"','" + "Admin" +"','"+credits.Text + "','" + prereq.Text +"') ";

您的查询语法完全错误。

于 2013-05-14T11:10:15.847 回答
0

修改您的Insert查询,例如

string query1 = "insert into Courses(CRN,CourseName,StudyLevel,Capacity,Instructor,Credits,Prerequisite) values ("
        + courseID.Text + ",'" + courseName.Text + "'," + studyLevel.SelectedValue + "," + capacity.Text + "," + "Admin," + credits.Text + "," + prereq.Text + ")";

第二个问题

如果它已保存,ExecuteNonQuery则将返回您1else 0,因此通过使用 return 的值,您可以检查并应用您的条件。

希望你能理解。

于 2013-05-14T11:00:56.643 回答
0
protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection("Data Source=D1-0221-37-393\\SQLEXPRESS;Initial Catalog=RSBY;User ID=sa;Password=BMW@721");
        conn.Open();
        string EmployeeId = Convert.ToString(TextBox1.Text);
        string EmployeeName = Convert.ToString(TextBox2.Text);
        string EmployeeDepartment = Convert.ToString(DropDownList1.SelectedValue);
        string EmployeeDesignation = Convert.ToString(DropDownList2.SelectedValue);
        string DOB = Convert.ToString(TextBox3.Text);
        string DOJ = Convert.ToString(TextBox4.Text);
        SqlCommand cmd = new SqlCommand("insert into Employeemaster values('" + EmployeeId + "','" + EmployeeName + "','" + EmployeeDepartment + "','" + EmployeeDesignation + "','" + DOB + "','" + DOJ + "')", conn);
        cmd.ExecuteNonQuery();

    }
于 2015-10-26T06:23:40.517 回答