c# - 不允许从数据类型 nvarchar 到二进制的隐式转换。使用 CONVERT 函数运行此查询。

标签 c# asp.net sql visual-studio

我在处理这段代码时遇到了问题。在我的数据库中,我将 Passphase 列设置为 binary(20)。为了获得下面列出的代码,我遵循了一个教程,但我进行了相当多的调整以满足我的需要。我的问题是我不知道如何将密码存储为二进制而不是 nvarchar。

这是一个 SQL 服务器的注册页面,如果有区别的话。

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegDNMembershipConnectionString"].ConnectionString);
    con.Open();
    string insCmd = "Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country) VALUES (@AccountName,@Passphrase,@EmailAddress,@FullName,@Country)";
    SqlCommand insertUser = new SqlCommand(insCmd, con);
    insertUser.Parameters.AddWithValue("@AccountName", TextBoxUN.Text);
    insertUser.Parameters.AddWithValue("@Passphrase", TextBoxPass.Text);
    insertUser.Parameters.AddWithValue("@EmailAddress", TextBoxEA.Text);
    insertUser.Parameters.AddWithValue("@FullName", TextBoxFN.Text);
    insertUser.Parameters.AddWithValue("@Country", DropDownListCountry.SelectedItem.ToString());

最佳答案

我相信你想改变这个:

insertUser.Parameters.AddWithValue("@Passphrase", TextBoxPass.Text);

为此:

insertUser.Parameters.AddWithValue("@Passphrase",
    Encoding.Default.GetBytes(TextBoxPass.Text));

此外,请遵守 IDisposable 接口(interface)。你上面的代码更合适地写成:

using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegDNMembershipConnectionString"].ConnectionString))
{
    con.Open();
    string insCmd = "Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country) VALUES (@AccountName,@Passphrase,@EmailAddress,@FullName,@Country)";
    using (var insertUser = new SqlCommand(insCmd, con))
    {
        ...
    }
}

关于c# - 不允许从数据类型 nvarchar 到二进制的隐式转换。使用 CONVERT 函数运行此查询。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21286661/

相关文章:

mysql_result 返回文件名作为结果

c# - .NET core 3.0 System.IO.Ports SerialPort 在 RPI 上始终使用 5-10% CPU

asp.net - 如何向 ASP 按钮 PostBackUrl 添加参数?

c# - 如何防止泄漏抽象?

javascript - 用户提交表单后在 Web 应用程序上发送推送通知

c# - 如何在内容页可访问的 asp.net 母版页中注册程序集?

mysql - 如何获取每个产品/进入日期最近 4 周的数据

MySQL 分组依据缺失值

c# - 将字典分配给键值

c# - 使用 C# 在 Excel 中创建图表