我正在开发一个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