我使用SQL Server 2016始终加密方法加密了现有数据,我们所拥有的列之一是NULLABLE但是从屏幕插入时它不接受NULL或空字符串。如果加密列在屏幕上不是强制性的,如何使其工作?
答案 0 :(得分: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();
}