How to insert Records in Database using C# language?

前端 未结 6 2111
孤独总比滥情好
孤独总比滥情好 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 17:55

    You should change your code to make use of SqlParameters and adapt your insert statement to the following

    string connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;
    // [ ] required as your fields contain spaces!!
    string insStmt = "insert into Main ([First Name], [Last Name]) values (@firstName,@lastName)";
    
    using (SqlConnection cnn = new SqlConnection(connetionString))
    {
        cnn.Open();
        SqlCommand insCmd = new SqlCommand(insStmt, cnn);
        // use sqlParameters to prevent sql injection!
        insCmd.Parameters.AddWithValue("@firstName", textbox2.Text);
        insCmd.Parameters.AddWithValue("@lastName", textbox3.Text);
        int affectedRows = insCmd.ExecuteNonQuery();
        MessageBox.Show (affectedRows + " rows inserted!");
    }
    

提交回复
热议问题