Executing query with parameters

前端 未结 5 792
-上瘾入骨i
-上瘾入骨i 2020-11-28 14:46

I want to execute a .sql script from C#. Basically the script inserts a row into few different tables.

The point is I have values in C# code that I need

5条回答
  •  粉色の甜心
    2020-11-28 14:59

    You'll need the System.Data.SqlCommand class.

    Change the fixed values to named parameters. For example:

    INSERT INTO [TABLE] (Column1) values (@Value1) // the @Value1 is the named parameter

    Example:

    var connection = new SqlConnection("connectionstring");
    var command = connection.CreateCommand();
    command.CommandText = "insert...."; // sql command with named parameters
    
    // set the named parameter values
    command.Parameters["@Value1"] = "Mark wa...";
    
    // execute 
    command.ExecuteNonQuery();
    

    SqlCommand reference: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx

提交回复
热议问题