Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert data into SQL Server from C# code

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 database. So how can I insert only to name, not id because id is auto increment?

I tried this

insert into student(id, name) values(,name) 

but it is not insert to my table.

This is my code :

protected void Button1_Click(object sender, EventArgs e)
{
    string test = txtName.Text;

    SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Person.mdf;Integrated Security=True;User Instance=True");

    string sql = "insert into student(name) values ('test')";

    try
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery();
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        string msg = "Insert Error:";
        msg += ex.Message;
    }
    finally
    {
        conn.Close();
    }
}
like image 271
titi Avatar asked Nov 29 '22 02:11

titi


1 Answers

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.

like image 133
David M Avatar answered Dec 06 '22 05:12

David M