Error when insert data from textbox to database

时间:2022-05-16 15:23:22

I have text and a button and when on submit, I am checking whether the database has any rows-if not then insert rows or else update them, but on submit its throwing an error saying incorrect syntax at "cmd.ExecuteNonQuery" in the else condition

我有文本和一个按钮,当提交时,我正在检查数据库是否有任何行 - 如果没有然后插入行或者更新它们,但是在提交时抛出错误说错误的语法在“cmd.ExecuteNonQuery”中的else条件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;


public partial class CM : System.Web.UI.Page
{
    DataSet ds = new DataSet();
    SqlDataAdapter da;
    SqlCommand cmd;
    DataTable dt;
    SqlConnection con = new SqlConnection("server =consulting76\\SQLEXPRESS; database = msdb; Integrated Security=True; MultipleActiveResultSets=True");

    protected void Page_Load(object sender, EventArgs e)
    {
        da = new SqlDataAdapter("Select * from NOTESMAKER", con);
        da.Fill(ds);
        //dt = ds.Tables["NOTESMAKER"];
    }

    protected void Button1_Click(object sender, EventArgs e)
    {   
        con.Open();
        if (ds.Tables[0].Rows.Count == 0)
        {
            cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values(@text1)",con);
            cmd.Parameters.Add(new SqlParameter("@text1", SqlDbType.NText)).Value = TextBox1.Text;
            da.InsertCommand = cmd;
            cmd.ExecuteNonQuery();
        }
        else
        {
            cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = @text1)",con);
            cmd.Parameters.Add(new SqlParameter("@text1", SqlDbType.NText)).Value = TextBox1.Text;
            da.UpdateCommand = cmd;
            cmd.ExecuteNonQuery();
        }
        con.Close();
    }

}

1 个解决方案

#1


5  

You are closing a bracket on this line, which is never opened:

您正在关闭此行的括号,该行从未打开:

cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = @text1)",con);

Also, setting the InsertCommand and UpdateCommand properties of the data adapter isn't neccessary.

此外,不需要设置数据适配器的InsertCommand和UpdateCommand属性。

#1


5  

You are closing a bracket on this line, which is never opened:

您正在关闭此行的括号,该行从未打开:

cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = @text1)",con);

Also, setting the InsertCommand and UpdateCommand properties of the data adapter isn't neccessary.

此外,不需要设置数据适配器的InsertCommand和UpdateCommand属性。