Insert data into SQL Server from C# code

前端 未结 7 1863
自闭症患者
自闭症患者 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:16

    I was facing this problem and after trying various solution found at stack overflow, i could summarize the experience as follows: commands executed in command shell of mssql like:

    insert into table_name (val1,val2,val3,val4) VALUES ("val1","val2",0,"val4")

    go

    or

    insert into table_name VALUES ("val1","val2",0,"val4")

    go
    

    work when typed directly in the mssql database prompt,

    But when it is required to use the the insert statement from c#, it is required to be kept in mind that string needs to be surrounded by an additional pair of single quites, around the strings, like in:

    SqlConnection cnn;
    
    string connetionString = "Data Source=server_name;Initial Catalog=database_name;User ID=User_ID;Password=Pass_word";
    
    cnn = new SqlConnection(connetionString);
    
    SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('val1','val2',0,'val4');", cnn);
    
    //or
    //SqlCommand myCommand = new SqlCommand(insert into table_name VALUES ('val1','val2',0,'val4');", cnn);
    
    cnn.Open();
    
    myCommand.ExecuteNonQuery();
    
    cnn.Close();
    

    the problem here is that most people, like myself, try to use <\"> in the place of double quotes <">that is implemented as in the above command line case, and SQL executor fails to understand the meaning of this.

    Even in cases where a string needs to be replace, ensure that strings are surrounded by single quotation, where a string concatination looks like a feasible solution, like in:

    SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('"+val1+"','val2',0,'val4');", cnn);
    

提交回复
热议问题