我已经使用 SQL Server 2016 始终加密方法加密了现有数据,我们拥有的列之一是 NULLABLE,但是从屏幕插入时它不接受 NULL 或空字符串。如果屏幕上不强制加密列,如何使其工作?
问问题
1715 次
1 回答
0
您看到的错误不正确,请确保您正确传递参数。这是一些有关如何执行此操作的示例代码。
架构:
CREATE TABLE [dbo].[SO](
[ssn] [nvarchar](9) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [CEK_Auto1], ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NULL
)
GO
CREATE PROCEDURE dbo.insertSP @ssn nvarchar(9)
AS
INSERT INTO [dbo].[SO] ([SSN]) VALUES (@SSN);
GO
C#代码:
SqlConnectionStringBuilder strbldr = new SqlConnectionStringBuilder();
strbldr.DataSource = ".";
strbldr.InitialCatalog = @"exptdb";
strbldr.IntegratedSecurity = true;
strbldr.ColumnEncryptionSetting = SqlConnectionColumnEncryptionSetting.Enabled;
string ssn = "";
using (var conn = new SqlConnection(strbldr.ConnectionString))
using (var command = conn.CreateCommand()) {
command.CommandType = CommandType.StoredProcedure;
command.CommandText = @"dbo.insertSP";
SqlParameter paramSSN = command.CreateParameter();
paramSSN.ParameterName = "@ssn";
paramSSN.SqlDbType = SqlDbType.NVarChar;
paramSSN.Direction = ParameterDirection.Input;
paramSSN.Value = ssn;
paramSSN.Size = 9;
command.Parameters.Add(paramSSN);
conn.Open();
command.ExecuteNonQuery();
}
请注意,在上述场景中,如果
string ssn = "";
那么查询成功,但是如果
string ssn = null;
您应该会看到执行失败
附加信息:过程或函数“insertSP”需要参数“@ssn”,但未提供该参数。
即使 ssn 列是明文也会发生此故障
您可以按如下方式在加密列中插入空值,因为空值未加密:
using (var conn = new SqlConnection(strbldr.ConnectionString))
using (var command = conn.CreateCommand()) {
command.CommandText = @"INSERT INTO [dbo].[SO] ([SSN]) VALUES (null)";
conn.Open();
command.ExecuteNonQuery();
}
于 2017-05-17T18:30:37.737 回答