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

时间:2012-10-12 01:00:32

标签: c# .net sql-server tsql

我收到错误:

  

无法将参数值从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);
        }

2 个答案:

答案 0 :(得分:7)

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

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

Command对象会自动为您处理。

答案 1 :(得分:1)

应该是

createLogin.Parameters.AddwithValue("@parameter", parametervalue)

并删除其余的参数代码。

您无需使用AddWithValue代替Add(