【问题标题】:Updating entry in Database in Asp.net在 Asp.net 中更新数据库中的条目
【发布时间】:2018-02-19 18:43:55
【问题描述】:

我正在尝试在 aspx 页面上更新数据库中的条目。我有一个 aspx 页面,它显示具有三个属性的项目。当我单击编辑项目以更新一个或所有属性并单击更新时,我收到以下错误:

System.Data.SqlClient.SqlException: ''('.' 附近的语法不正确

我的aspx代码如下:

<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <div class="col-lg-12">
            <div class="form-group alert alert-warning">
               <asp:label runat="server" ID="lblNewsEdits">Please edit news details below</asp:label>
            </div>
            <div class="form-group">
                <asp:TextBox name="txtTitle" id="txtTitle" tabindex="1" class="form-control" placeholder="Title" value="" runat="server"></asp:TextBox>
            </div>
            <div class="form-group">
                <asp:TextBox name="txtDate" id="txtDate" tabindex="1" class="form-control" placeholder="Enter Today Date DD/MM/YYYY" value="" runat="server"></asp:TextBox>
            </div>
            <div class="form-group">
                <asp:TextBox namee="txtNewscontent" name="txtNewscontent" id="txtNewscontent" tabindex="2" class="form-control" placeholder="News Content" runat="server"></asp:TextBox>
            </div>
            <div class="form-group">
                <div class="row">
                    <div class="col-sm-6 col-sm-offset-3">
                        <input type="submit" name="btnEdit" id="btnEdit" tabindex="1" class="form-control btn btn-warning" value="Edit"/>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-1 col-md-offset-11">
                        <a href="/Backend/Default.aspx" class="btn btn-default pull-right">Back</a>
                    </div>
                </div>    
            </div>
        </div>
    </div>
</div>

我的 aspx.cs 代码是:

 protected void Page_Load(object sender, EventArgs e)
    {
        {
            string q = Request.QueryString["id"];
            int id = 0;
            int.TryParse(q, out id);

            if (Session["username"] == null)
                Response.Redirect("Login.aspx");

            if (IsPostBack)
            {
                EditNews(id);
                Response.Redirect("~/Backend");
            }
            else
            {
                PopulateNews(id);
            }
        }
    }
    private void EditNews(int id)
    {
        //Create a SQL Connection - get the connection string from the web.config
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString);
        //define the SQL statement you wish to run - use @ placeholders to populate parameters
        string sqlStatement = "UPDATE News (Title, DatePosted, NewsContent) Values (@Title,@DatePosted,@NewsContent);";
        //Set up the SQL Command
        SqlCommand command = new SqlCommand(sqlStatement, connection);
        //Populate the placeholders with parameter values
        command.Parameters.AddWithValue("@Title", txtTitle.Text);
        command.Parameters.AddWithValue("@DatePosted", Convert.ToDateTime(txtDate.Text));
        command.Parameters.AddWithValue("@NewsContent", txtNewscontent.Text);
        //open a connection to the database (NOTE! dont forget to close this when you are done)
        connection.Open();
        //Run the SQL statement against the database
        command.ExecuteNonQuery();
        command.Dispose();
        //NOTE! close the connection
        connection.Close();
    }
    private void PopulateNews(int id)
    {
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString);
        connection.Open();
        string query = "SELECT Title, DatePosted, NewsContent FROM News WHERE Id = @id";

        SqlCommand command = new SqlCommand(query, connection);
        command.Parameters.AddWithValue("@id", id);
        SqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            txtTitle.Text = reader["Title"].ToString();
            txtDate.Text = reader["DatePosted"].ToString();
            txtNewscontent.Text = reader["NewsContent"].ToString();
        }
        reader.Close();
        connection.Close();
    }

我的表格属性是:

CREATE TABLE [dbo].[News] (
[Id]          INT            IDENTITY (1, 1) NOT NULL,
[Title]       NVARCHAR (100) NOT NULL,
[DatePosted]  DATE           NOT NULL,
[NewsContent] NTEXT          NOT NULL,
[IsRead]      BIT            DEFAULT ((0)) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

有什么想法吗?

【问题讨论】:

    标签: asp.net sql-update


    【解决方案1】:

    您的Update 声明是错误的。

    将其替换为Insert into。它会工作

    所以,而不是

    string sqlStatement = "UPDATE News (Title, DatePosted, NewsContent) Values (@Title,@DatePosted,@NewsContent);";
    

    你需要

    string sqlStatement = "Insert into News (Title, DatePosted, NewsContent) Values (@Title,@DatePosted,@NewsContent);";
    

    如果你真的需要update 查询它们,它的语法是不同的

    Update TableName Set Field1=@value1, … Where ConditionHere
    

    【讨论】:

    • 非常感谢,效果很好。再次感谢 Surjit。
    【解决方案2】:

    您的更新语句的语法不正确。

    UPDATE News (Title, DatePosted, NewsContent) Values (@Title,@DatePosted,@NewsContent);
    

    应该是

    UPDATE News 
    SET Title = @Title, DatePosted = @DatePosted, NewsContent = @NewsContent
    WHERE -- some discriminator here like match on ID
    

    如果您打算进行插入(添加),那么语法应该是

    INSERT INTO News (Title, DatePosted, NewsContent) Values (@Title,@DatePosted,@NewsContent);
    

    一个额外的建议。如果一个类型实现了接口IDisposable,那么最好将该实例包装在using 块中,以确保始终释放外部资源。 SqlConnectionSqlCommandSqlDataReader 都实现了 IDisposable。示例:

    using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString) 
    {
        // rest of code here
    }
    

    现在连接总是关闭和释放,即使Exception被抛出,一旦块退出。

    【讨论】:

      猜你喜欢
      • 2016-05-16
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多