我在处理这段代码时遇到了问题。在我的数据库中,我将 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/