如何使用c#将行插入SQL Server 2005

时间:2022-04-10 15:33:00

I am using VS 2008 and SQL Server 2005. I am using below code to insert a row to a table.

我正在使用VS 2008和SQL Server 2005.我使用下面的代码向表中插入一行。

Table is TestTable, and it has a single column Name (varchar(50)).

表是TestTable,它有一个列Name(varchar(50))。

I am totally new to c# coding, please help me in this.

我对c#编码全新,请帮助我。

protected void Button1_Click(object sender, EventArgs e)
{
    try
    {
        string sql = "insert into TestTable(Name) values (vinayak)";
        using (SqlConnection conn = new SqlConnection("Data Source=VINAYAK-PC;Initial Catalog=TestTable;Integrated Security=True;"))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                cmd.Parameters.AddWithValue("@Name", "test"); // assign value to parameter 
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (SqlException ex)
    {
        string msg = "Insert Error:";
        msg += ex.Message;
    }
}

2 个解决方案

#1


2  

You haven't included the parameter in the SQL statement.

您尚未在SQL语句中包含该参数。

Change vinayak to @Name.

将vinayak更改为@Name。

#2


0  

In table "TestTable" if you have only one column "Name" and you want to insert value "vinayak" in that then include vinayak in single quotes and you do not need to execute following statement -:

在表“TestTable”中,如果您只有一列“名称”,并且您想在其中插入值“vinayak”,那么将vinayak包含在单引号中,您不需要执行以下语句 - :

cmd.Parameters.AddWithValue("@Name", "test");

if you want to use parameter in your sql command then make sure u prefix "@" before "name" in your sql command.

如果你想在你的sql命令中使用参数,那么确保你在sql命令中的“name”之前加上“@”前缀。

see this link

看到这个链接

#1


2  

You haven't included the parameter in the SQL statement.

您尚未在SQL语句中包含该参数。

Change vinayak to @Name.

将vinayak更改为@Name。

#2


0  

In table "TestTable" if you have only one column "Name" and you want to insert value "vinayak" in that then include vinayak in single quotes and you do not need to execute following statement -:

在表“TestTable”中,如果您只有一列“名称”,并且您想在其中插入值“vinayak”,那么将vinayak包含在单引号中,您不需要执行以下语句 - :

cmd.Parameters.AddWithValue("@Name", "test");

if you want to use parameter in your sql command then make sure u prefix "@" before "name" in your sql command.

如果你想在你的sql命令中使用参数,那么确保你在sql命令中的“name”之前加上“@”前缀。

see this link

看到这个链接