我試圖檢查用戶是否存在於SQL Server中的表內。我已經創建連接字符串,打開的連接 -ExecuteScalar SQLException:標量變量未聲明
var settings = ConfigurationManager.ConnectionStrings["BlogEngine"].ConnectionString;
SqlConnection conn = new SqlConnection(settings);
using (conn)
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
var checkUser = "SELECT COUNT(*) FROM dbo.be_Users WHERE UserName = @UserName";
using (SqlCommand userquery = new SqlCommand(checkUser,conn))
{
var parma = userquery.Parameters;
parma.AddWithValue("@UserName", activedirectory.DisplayName);
int UserExist = (int)userquery.ExecuteScalar();
if (UserExist > 0)
{
//Username exist
AuthenticateUser(staffId, password, rmb);
}
else
{
//Username doesn't exist.
var sqlQuery = "INSERT INTO dbo.be_Users (BlogID, UserName, Password, LastLoginTime, EmailAddress, Department)" + "VALUES (@BlogID, @UserName, @Password, @LastLoginTime, @EmailAddress, @Department)";
using (SqlCommand qe = new SqlCommand(sqlQuery))
{
var parms = qe.Parameters;
parms.AddWithValue("@BlogID", Blog.CurrentInstance.Id.ToString());
parms.AddWithValue("@UserName", activedirectory.DisplayName);
parms.AddWithValue("@Password", (passwordFormat == MembershipPasswordFormat.Hashed ? Utils.HashPassword(DEFAULT_PASSWORD) : DEFAULT_PASSWORD));
parms.AddWithValue("@LastLoginTime", DateTime.Now);
parms.AddWithValue("@EmailAddress", DEFAULT_EMAIL);
parms.AddWithValue("@Department", activedirectory.department);
qe.ExecuteNonQuery();
}
AuthenticateUser(staffId, password, rmb);
}
}conn.Close();
}
我不斷收到此錯誤 - 類型「System.Data.SqlClient.SqlException」的異常出現在System.Data.dll中,但在用戶代碼中沒有處理
附加信息:必須聲明標量變量「@UserName」。
在行處發生異常。
請問我該如何解決?
嗯......爲什麼呢?有原因嗎?特別是有沒有與這個問題有關的原因?我會**不會**期望這種改變對問題中報告的問題產生任何影響。 –