我正在開發一個web應用程序並遇到問題。當有人試圖(成功或失敗)登錄時,我需要將用戶名和IP地址插入到SQL數據庫表「日誌」中。 ID,時間和日期被自動插入... 出於某種原因,我無法使用我的登錄表單工作。 INSERT語句工作正常,如果我從另一個表單啓動它,但我不能與它用於檢查登錄憑證的SELECT語句一起工作。SQL多重語句,INSERT不能正常工作
我嘗試了不同的解決方案,但沒有一個將數據插入到表中......它不會引發錯誤,它只是不會將新行插入「日誌」表中。
任何幫助表示讚賞。 :)
protected void btnLog_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConn"].ToString()))
{
string username = null;
string password = null;
string ipAddress = null;
SymCryptography cryptic = new SymCryptography();
SqlCommand cmdSelect = new SqlCommand();
SqlCommand cmdLog = new SqlCommand();
SqlDataReader myReader = null;
cmdSelect.Connection = conn;
cmdLog.Connection = conn;
cmdSelect.CommandText = "SELECT * FROM uporabniki WHERE [email protected]_ime AND [email protected]";
cmdSelect.CommandType = CommandType.Text;
cmdLog.CommandText = "INSERT INTO log (up_ime, ip) VALUES (@up_ime, @ip)";
cmdLog.CommandType = CommandType.Text;
cmdSelect.Parameters.Add("@up_ime", SqlDbType.NVarChar, 20).Value = tbUsr.Text;
cmdSelect.Parameters.Add("@geslo", SqlDbType.NVarChar, 20).Value = cryptic.Encrypt(tbPwd.Text);
cmdLog.Parameters.Add("@up_ime", SqlDbType.NVarChar, 20).Value = tbUsr.Text;
cmdLog.Parameters.Add("@ip", SqlDbType.NVarChar, 20).Value = ipAddress;
conn.Open();
try
{
//cmdLog.ExecuteNonQuery(); I tried it here, but it doesn't work
myReader = cmdSelect.ExecuteReader();
if (myReader.Read())
{
username = myReader["up_ime"].ToString();
password = myReader["geslo"].ToString();
Session["rights"] = myReader["pravice"];
Session["login"] = "OK";
pravice = true;
}
myReader.Close();
//cmdLog.ExecuteNonQuery(); I tried it here, but it doesn't work
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
}
//I tried to open connection again, but stil INSERT does not work
/* using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConn"].ToString()))
{
string ipAddress = null;
SqlCommand cmdLog = new SqlCommand();
cmdLog.Connection = conn;
cmdLog.CommandText = "INSERT INTO log (up_ime, ip) VALUES (@up_ime, @ip)";
cmdLog.CommandType = CommandType.Text;
cmdLog.Parameters.Add("@up_ime", SqlDbType.NVarChar, 20).Value = tbUsr.Text;
cmdLog.Parameters.Add("@ip", SqlDbType.NVarChar, 20).Value = ipAddress;
conn.Open();
try
{
cmdLog.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
}
if (pravice == true)
{
Response.Redirect("Default.aspx");
}
else
{
Response.Redirect("Login.aspx");
}*/
}
你是否收到某種錯誤信息? – Pieter
日誌表上的任何約束(如唯一鍵或主鍵)? – hcb
我沒有看到眼前的問題,但我建議您將此代碼從您的單擊事件中提取出來,並放入另一個可以調用的類中。讓SQL亂丟你的事件處理程序通常不是一個好習慣。 – taylonr