猜猜插入语句中的错误

时间:2011-01-11 06:59:51

标签: c# asp.net sql insert connection-string

有人带着一些鹰眼吗?我想在下面的插入语句中删除错误的位置。我在运行时使用了断点来跟踪代码,并且我得到了异常错误(在关键字“Case”附近有一个不正确的语法)。让你的老鹰眼睛......

public partial class OpenCase : System.Web.UI.Page
{
    string adminString;
    protected void Page_Load(object sender, EventArgs e)
    {
        adminString = "CA123";
    }

    protected void openCaseBotton_Click(object sender, EventArgs e)
    {
        //SQL connection string
        SqlDataSource CSMDataSource = new SqlDataSource();
        CSMDataSource.ConnectionString = ConfigurationManager.ConnectionStrings["CMSSQL3ConnectionString"].ToString();

        //SQL Insert command with variables
        CSMDataSource.InsertCommandType = SqlDataSourceCommandType.Text;
        CSMDataSource.InsertCommand = "INSERT INTO Case (CaseID, CaseDesc, DateOpened, CasePriority, AdministratorID) VALUES (@CaseID, @CaseDesc, @DateOpened, @CasePriority, @AdministratorID)";

        //Actual Insertion with values from textboxes into databse fields
        CSMDataSource.InsertParameters.Add("CaseID", caseIDTextBox.Text);
        CSMDataSource.InsertParameters.Add("CaseDesc", caseDescTextBox.Text);
        CSMDataSource.InsertParameters.Add("DateOpened", DateTime.Now.ToString());
        CSMDataSource.InsertParameters.Add("CasePriority", null);
        CSMDataSource.InsertParameters.Add("AdministratorID", adminString.ToString());

        int rowsCommitted = 0;

        //Try catch method to catch exceptions during insert
        try
        {
            rowsCommitted = CSMDataSource.Insert();
            Response.Write(@"<script language='javascript'>alert('The following errors have occurred:');</script>");
        }

        catch (Exception ex)
        {
            //error message displayed when exception occurs


            string script = "<script>alert('" + ex.Message + "');</script>";
            Response.Write("The following Error occurred while entering the records into the database" + " " + ex.ToString() + " ");
            Response.Redirect("~/ErrorPage.aspx", false);
        }
        finally
        {
            CSMDataSource = null;
        }

        //Where to go next if insert was successful or failed
        if (rowsCommitted != 0)
        {
            Response.Redirect("~/CaseAdmin.aspx", false);
        }
        else
        {

            Response.Redirect("~/ErrorPage.aspx", false);
        }

    }

    protected void addExhibitBotton_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/EntryForms/AddExhibit.aspx", false);

    }
}

看到什么?可能你需要一个C#错误视力护目镜......大声笑

2 个答案:

答案 0 :(得分:7)

INSERT附近?好吧,CASE是一个SQL保留字,所以请简单地尝试:

CSMDataSource.InsertCommand = "INSERT INTO [Case] (...

告诉它Case是一个对象名,而不是SQL关键字。

答案 1 :(得分:4)

我非常确定case实际上是一个SQL关键字。

根据DBMS的不同,您可能需要执行一些操作,例如将其括在反引号或其他分隔符中,以告诉执行引擎将其视为非关键字,例如:

CSMDataSource.InsertCommand = "INSERT INTO `Case` (CaseID, ...