Insert data into SQL Server from C# code

前端 未结 7 1858
自闭症患者
自闭症患者 2021-01-06 06:59

I have a table student (id, name). Then I have one textbox, for entering the name, when click on submit button, it inserts the data into the databa

相关标签:
7条回答
  • 2021-01-06 07:23
    INSERT INTO student (name) values ('name')
    

    Omit the id column altogether, it will be populated automatically. To use your variable, you should parameterise your SQL query.

    string sql = "INSERT INTO student (name) values (@name)";
    conn.Open();
    SqlCommand cmd = new SqlCommand(sql, conn);
    cmd.Parameters.Add("@name", SqlDbType.VarChar);
    cmd.Parameters["@name"].Value = test;
    cmd.ExecuteNonQuery();
    

    You should never attempt to do this by constructing a SQL string containing the input value, as this can expose your code to SQL injection vulnerabilities.

    0 讨论(0)
提交回复
热议问题