Cql中的SqlCommand和连接出错

时间:2017-04-27 17:47:32

标签: c# sql-server

我的代码有错误,但无法找到问题。请帮忙。

SqlConnection myConnection = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Software Project\BakeryProject Pages\BakeryProject\Databases\Users.mdf; Integrated Security = True");

myConnection.Open();

string commandText = "INSERT INTO Table (Id, Username, First_name, Last_Name, Password, Client, Staff, Admin )";
commandText += "VALUES (1, 'JohnSmith', 'John', 'Smith', 'Pass1', 'Client');";

SqlCommand myCommand = new SqlCommand(commandText, myConnection);
myCommand.Parameters.AddWithValue("@Id", mID);
myCommand.Parameters.AddWithValue("@Username", mUsername);
myCommand.Parameters.AddWithValue("@First_name", mNameFirst);
myCommand.Parameters.AddWithValue("@Last_name", mNameLast);
myCommand.Parameters.AddWithValue("@Password", mPassword);
myCommand.Parameters.AddWithValue("@Client", mClient);

myCommand.ExecuteNonQuery();

1 个答案:

答案 0 :(得分:2)

您正在尝试添加参数,但您从未在查询中定义任何参数。也许这就是你的意思:

string commandText = "INSERT INTO [Table] (Id, Username, First_name, Last_Name, Password, Client) ";
       commandText += "VALUES (@Id, @Username, @First_name, @Last_name, @Password, @Client);";

SqlCommand myCommand = new SqlCommand(commandText, myConnection);
myCommand.Parameters.AddWithValue("@Id", mID);
myCommand.Parameters.AddWithValue("@Username", mUsername);
myCommand.Parameters.AddWithValue("@First_name", mNameFirst);
myCommand.Parameters.AddWithValue("@Last_name", mNameLast);
myCommand.Parameters.AddWithValue("@Password", mPassword);
myCommand.Parameters.AddWithValue("@Client", mClient);

myCommand.ExecuteNonQuery();

注意:我还从您的脚本中删除了StaffAdmin列,因为它们没有下面提到的参数。这应该会给你一个正确的方向。

作为旁注,通过使用字符串文字在C#中声明查询要容易得多。这样,您就不必处理+=和来自它的奇怪间距问题:

string commandText =
@"
Insert  [Table] (Id, Username, First_name, Last_Name, Password, Client)
Values  (@Id, @Username, @First_name, @Last_name, @Password, @Client);      
";