[英]How to insert an integer into a database through command prompt
我正在嘗試使用以下代碼在C#中將整數插入數據庫中,但是每次運行編譯器時,都會通知我我的整數不是有效的列“無效的列名UserID”
有人對此有見識嗎? 謝謝。
Console.WriteLine("Please enter a new User Id");
string line = Console.ReadLine();
int UserID;
if (int.TryParse(line, out UserID))
{
Console.WriteLine(UserID);
Console.ReadLine();
}
//Prepare the command string
string insertString = @"INSERT INTO tb_User(ID,f_Name, l_Name) VALUES (UserID,'Ted','Turner')";
首先,如果您不打算使用存儲過程,那么我會養成使用參數化查詢的習慣。 在您的示例中,我將:
using (var command = new SqlCommand("INSERT INTO tb_User(ID, f_Name, l_Name) VALUES (@id, @forename, @surname)", conn))
{
command.Parameters.AddWithValue("id", id);
command.Parameters.AddWithValue("forename", forename);
command.Parameters.AddWithValue("surname", surname);
command.ExecuteNonQuery();
}
其中id
, forename
, surname
是適當的變量。 注意,我也在使用using
塊,這可以確保對象完成后被清理。
這是因為insertString中的'UserID':...“ VALUES(UserID” ...)無效。
您需要為UserID傳遞一個值,例如:...“ VALUES('myUserIDGoesHere'” ...
您的字符串不是動態讀取變量。 使用這樣的東西:
字符串insertString = string.Format(@“ INSERT INTO tb_User(ID,f_Name,l_Name)VALUES({0},'{1}','{2}')”,UserId,“ Ted”,“ Turner”);
有更好的方法,這取決於您使用的是哪種類型的數據訪問,但這只是為了指出如何糾正字符串。
無論使用哪種方法,都要回答您的問題,請嘗試:
string insertString = @"INSERT INTO tb_User(ID,f_Name, l_Name) VALUES ("
+ UserID + ",'Ted','Turner')";
問題是VALUES
的第一個參數-只是沒有定義。 如果這是用戶輸入的值,則需要在命令中添加一個參數 ,然后在SQL中使用該參數。 例如:
cmd.Parameters.AddWithValue("@id", UserID);
然后使用
VALUES(@id, ...
在TSQL中。
另外, 通常您可能希望系統生成唯一的ID。 最簡單的級別可能是定義了IDENTITY
(自動序列)。
使用參數化查詢:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var insertCommand = new SqlCommand(
@"INSERT INTO tb_User (ID, f_Name, l_Name)
VALUES (@ID, 'Ted', 'Turner')", connection))
{
insertCommand.Parameters.AddWithValue("@ID", userID);
insertCommand.ExecuteNonQuery();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.