gpt4 book ai didi

c# - 无法将参数值从SqlParameter转换为String

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:06 25 4
gpt4 key购买 nike

我得到错误:


  无法将参数值从SqlParameter转换为String。


我通过:

TestUsername,
TestPassword,
TestFirstName,
TestLastName,
TestEmail@Email.Com


码:

        try
{

Console.WriteLine("Inputs: Username, Password, First Name, Last Name, Email");
Console.WriteLine("Username: ");
string usernameInput = Console.ReadLine();
Console.WriteLine("Password: ");
string passwordInput = Console.ReadLine();
Console.WriteLine("First Name: ");
string firstNameInput = Console.ReadLine();
Console.WriteLine("Last Name: ");
string lastNameInput = Console.ReadLine();
Console.WriteLine("Email: ");
string emailInput = Console.ReadLine();

SqlCommand createLogin = new SqlCommand("INSERT INTO [dbo].[Users] VALUES ('@username', '@password', '@firstname', '@lastname', '@email')", myConnection.SqlConnection);
SqlParameter usernameParam = createLogin.Parameters.Add("@username", SqlDbType.VarChar, 40);
SqlParameter passwordParam = createLogin.Parameters.Add("@password", SqlDbType.VarChar, 50);
SqlParameter firstNameParam = createLogin.Parameters.Add("@firstname", SqlDbType.VarChar, 40);
SqlParameter lastNameParam = createLogin.Parameters.Add("@lastname", SqlDbType.VarChar, 40);
SqlParameter emailParam = createLogin.Parameters.Add("@email", SqlDbType.VarChar, 40);

usernameParam.Value = usernameInput;
passwordParam.Value = passwordInput;
firstNameParam.Value = firstNameInput;
lastNameParam.Value = lastNameInput;
emailParam.Value = emailParam;


createLogin.ExecuteNonQuery();
Console.WriteLine("Username: {0} with Password: {1} created.", usernameInput, EncDec.Decrypt(passwordInput, "testEncryption"));
}
catch (Exception CreateLoginException)
{
Console.WriteLine(CreateLoginException);
}

最佳答案

您可以声明参数并设置值。代码的唯一问题是,您已将参数括在单引号中,这使它成为字符串而不是参数。在查询中删除参数周围的单引号,

SqlCommand createLogin = new SqlCommand(
"INSERT INTO [dbo].[Users]
VALUES (@username, @password, @firstname, @lastname, @email",
myConnection.SqlConnection);


Command对象自动为您处理它。

关于c# - 无法将参数值从SqlParameter转换为String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12850818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com