简体   繁体   English

如何使用SqlBulkCopy填充数据库中的加密列?

[英]How to fill encrypted columns in database using SqlBulkCopy?

I'm using SqlBulkCopy and System.Data.Datatable to insert data into my database. 我正在使用SqlBulkCopySystem.Data.Datatable将数据插入到我的数据库中。 I'm doing something like this: 我正在做这样的事情:

var table = new DataTable();

// Creating table schema
var newRow = table.NewRow();
newRow["FirstName"] = Parser.Parse(values[0])
newRow["LastName"] = Parser.Parse(values[1])
...
newRos["SSN"] = //here I need to encrypt by db certificate value[5] before set it to this row value

And simple copy to db code: 并简单地复制到db代码:

using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction))
{
    bulkCopy.BatchSize = 100;
    bulkCopy.DestinationTableName = "dbo.Member";
    try
    {    
        bulkCopy.WriteToServer(table);
    }
    catch (Exception)
    {
        transaction.Rollback();
        connection.Close();
        throw;
    }
}

Of course I can set encrypted column later using a stored procedure in the database, but I want to do this in one transaction. 当然,稍后我可以使用数据库中的存储过程来设置加密列,但是我想在一个事务中执行此操作。 Is it possible to encrypt string value using my certificate from the database in code? 是否可以使用代码中的数据库证书来加密string值?

Thanks in advance! 提前致谢!

As I see this, you can choose one of the following options (which should be both easy to implement): 正如我所看到的,您可以选择以下选项之一(应该都易于实现):

Do the encryption in your C# code 在您的C#代码中进行加密

Since you have all the data there, you can make the encryption there using .NET Framework relevant classes. 由于那里有所有数据,因此可以使用.NET Framework相关类在此处进行加密。 You can test it and make sure you get the same result. 您可以对其进行测试,并确保获得相同的结果。

Use AFTER INSERT trigger 使用AFTER INSERT触发器

After adding the value, you'll modify and add the encrypted data. 添加值后,您将修改并添加加密的数据。 The trigger will be part of the same transaction. 触发器将是同一事务的一部分。 Just use CREATE TRIGGER statement to create a new trigger, check if the value is NULL and then put the encrypted value using SQL statements. 只需使用CREATE TRIGGER语句创建一个新触发器,检查该值是否为NULL,然后使用SQL语句放置加密后的值。

For Example: 例如:

CREATE TRIGGER [dbo].[myTrigger]
   ON  [dbo].[Members] 
   AFTER INSERT
AS 
BEGIN
    SET NOCOUNT ON;
    UPDATE Members
    SET [EncryptedSSN] = EncryptByKey(Key_GUID('SSN_Key'), inserted.SSN)
    FROM inserted 
    INNER JOIN dbo.Members On inserted.id = Members.id
END 

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM