由於您在SqlCommand
中聲明瞭Id
參數,但未添加任何值。
而當您在CommandText
屬性中分配文本時,不需要使用()
。
cmd.CommandText = "SELECT Goal from Planning WHERE Id = @Id";
cmd.Parameters.AddWithValue("@Id", YourIdValue);
int goal = (int)cmd.ExecuteScalar();
還可以使用using
statement處置您的SqlConnection
和SqlCommand
。
這裏有一個完整的例子;
using(SqlConnection con = new SqlConnection(connString))
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT Goal from Planning WHERE Id = @Id";
cmd.Parameters.AddWithValue("@Id", YourIdValue);
try
{
conn.Open();
int goal = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
第一行是您的錯誤信息給的值? – Olli
是的,這是我的第一個錯誤信息 – qU3st
順便說一句,你的_connection string_似乎也是錯誤的。如果你的'connectionstring'是一個_variable_,你應該像'new SqlConnection(connectionstring)'而不是'new SqlConnection(@「connectionstring」)''一樣使用它。 –