How to insert Records in Database using C# language?

前端 未结 6 2082
孤独总比滥情好
孤独总比滥情好 2020-12-01 17:26

I am just a begginer on C# so i need too much help. Now the problem is that i have designed a windows form in which there are many fields like first name, last name, address

6条回答
  •  [愿得一人]
    2020-12-01 18:12

    Use a parameterized query to prevent Sql injections (secutity problem)

    Use the using statement so the connection will be closed and resources will be disposed.

    using(var connection = new SqlConnection("connectionString"))
    {
        connection.Open();
        var sql = "INSERT INTO Main(FirstName, SecondName) VALUES(@FirstName, @SecondName)";
        using(var cmd = new SqlCommand(sql, connection))
        {
            cmd.Parameters.AddWithValue("@FirstName", txFirstName.Text);
            cmd.Parameters.AddWithValue("@SecondName", txSecondName.Text);
    
            cmd.ExecuteNonQuery();
        }
    }
    

提交回复
热议问题