使用参数执行查询

Mar*_*cer 11 .net c# sql

我想.sql从C#执行一个脚本.基本上,脚本会在几个不同的表中插入一行.

关键是我在C#代码中有值,我需要传递给.sql查询.这些值将在程序执行期间收集.

这是我想从C#代码执行的查询:

INSERT INTO [DB].[dbo].[User]
           ([Id]
           ,[AccountId]
           ,[FirstName]
           ,[LastName]
           ,[JobTitle]
           ,[PhoneNumber]
          )
     VALUES
           ('00A640BD-1A0D-499D-9155-BA2B626D7B68'
           ,'DCBA241B-2B06-48D7-9AC1-6E277FBB1C2A'
           ,'Mark'
           ,'Wahlberg'
           ,'Actor'
           ,'9889898989'])
GO
Run Code Online (Sandbox Code Playgroud)

这些值会不时变化,即它们是用C#代码捕获的,需要通过.

任何人都可以帮我这样做..我正在学习C#和SQL.非常感谢.

Pau*_*ann 27

你可以在这里打开自己的SQL注入攻击,所以最好的做法是使用参数:

using (SqlConnection dbConn = new SqlConnection(connectionString))
{
    dbConn.Open();

    using (SqlTransaction dbTrans = dbConn.BeginTransaction())
    {
        try
        {
            using (SqlCommand dbCommand = new SqlCommand("insert into [DB].[dbo].[User] ( [Id], [AccountId], [FirstName], [LastName], [JobTitle], [PhoneNumber] ) values ( @id, @accountid, @firstname, @lastname, @jobtitle, @phonenumber );", dbConn))
            {
                dbCommand.Transaction = dbTrans;

                dbCommand.Parameters.Add("id", SqlType.VarChar).Value = id;
                dbCommand.Parameters.Add("accountid", SqlType.VarChar).Value = accountId;
                dbCommand.Parameters.Add("firstname", SqlType.VarChar).Value = firstName;
                dbCommand.Parameters.Add("lastname", SqlType.VarChar).Value = lastName;
                dbCommand.Parameters.Add("jobtitle", SqlType.VarChar).Value = jobTitle;
                dbCommand.Parameters.Add("phonenumber", SqlType.VarChar).Value = phoneNumber;

                dbCommand.ExecuteNonQuery();
            }

            dbTrans.Commit();
        }
        catch (SqlException)
        {
            dbTrans.Rollback();

            throw; // bubble up the exception and preserve the stack trace
        }
    }

    dbConn.Close();
}
Run Code Online (Sandbox Code Playgroud)

对于ADO.Net的初学者来说,这是一篇很好的文章

编辑 - 就像一些额外的信息,我已经添加了一个事务,所以如果SQL命令失败,它将回滚.