【问题标题】:How to use writing N for insert query in .NET C#?如何在 .NET C# 中使用编写 N 进行插入查询?
【发布时间】:2021-11-13 15:39:07
【问题描述】:

在 SQL Server 中

update incident_info 
set description = N'ဆေးလိပ်' 
where incidentid = 5

此查询在 SQL Server 中是正确的,并且在数据库中正确显示缅甸字体。

我想在下面的插入查询中编写正确的查询。

sqlUtil.SqlDataUpdate(false, ("INSERT INTO Incident_Info (incidentid, incidentdate, incidenttime, description, Salesmen_id, name, phone, email, address, cost, currency, solution, status)" +
            "VALUES (@incidentid, @incidentdate, @incidenttime, N'+@description+', @salesmenid, N'+@name+', @phone, @email, N'+@address+', @cost, @currency, N'+@solution+', @status)"), SysController.dicParams);

【问题讨论】:

  • 您只需将参数定义SqlDbType.NVarChar - 参数名称前不需要N.....。 sqlCmd.Parameters.Add("@description", SqlDbType.NVarChar, 100).Value = "......" - .NET 中的字符串默认已经是 Unicode 字符串

标签: c# .net sql-server


【解决方案1】:

不需要需要在您的 SQL 参数名称前加上 N 前缀 - 这是无用的,并且可能会导致错误。在原始 SQL 代码 sn-p 中指定 Unicode 字符串文字 时,需要 N 前缀。

在您的情况下,您需要确保实际插入 SQL Server 的代码将您的参数正确定义为SqlDbType.NVarChar。因此,在您的 sqlUtil 类中,某处有一个方法 SqlDataUpdate 可以解析并执行您发送的 SQL 语句。

在里面,你必须确保使用类似这样的代码:

using (SqlConnection conn = new SqlConnection(-your-connection-string-here-))
using (SqlCommand insertCmd = new SqlCommand(sqlQuery, conn))
{
    // here, you need to ensure you define your string parameters correctly
    insertCmd.Parameters.Add("@description", SqlDbType.NVarChar, 100);
    .....
    
    // and then you need to set the values - since .NET strings are inherently Unicode, no special treatment is needed
    insertCmd.Parameters["@description"].Value = SysController.dicParams.......
    .....
    
    // open, execute, close
    conn.Open();
    int rowsInserted = insertCmd.ExecuteNonQuery();
    conn.Close();
}

这必须在您的sqlUtil内部完成 - 您不能通过简单地在参数名称中添加N 前缀来从“外部”影响这一点。 ..

【讨论】:

  • 漂亮而简短的insertCmd.Parameters.Add("@description", SqlDbType.NVarChar, 100).Value = SysController.dicParams; 两行合二为一。而conn.Close(8); 是一个错字
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多