2015-02-24 68 views
0

我有一个表名是'User_tbl',其中我保存所有注册用户的数据,并且同一张表用于在登录期间验证用户。如何在登录后更新列'datetime'

我想在登录后只更新当前日期时间的'LastSeen'列。

看这张图片。

enter image description here

背后

protected void Submit(object sender, EventArgs e) 
     { 
      SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); 

      con.Open(); 
      SqlCommand cmd = new SqlCommand("select * from User_tbl where UserName [email protected] and [email protected]", con); 
      cmd.Parameters.AddWithValue("@username", txtUserName.Text); 
      cmd.Parameters.AddWithValue("@password", txtPWD.Text); 

      SqlDataAdapter da = new SqlDataAdapter(cmd); 
      DataTable dt = new DataTable(); 
      da.Fill(dt); 


      if (dt.Rows.Count > 0) 
      { 
       //to define the user seesion (starting user session) 

       Session["username"] = txtUserName.Text; 

       Response.Redirect("default2.aspx"); 

      } 

      else 

      { 

       ClientScript.RegisterStartupScript(Page.GetType(), "LoginValidate", "<script language='javascript'> document.getElementById('errorMessage').innerHTML = 'Invalid Username or Password'</script>"); 

      } 


     } 
+2

但是你没有阅读'dt'中的_that_列?也不要将您的密码存储为纯文本。阅读:http://stackoverflow.com/questions/1054022/best-way-to-store-password-in-database – 2015-02-24 12:54:39

+1

最好不要使用AddWithValue - 请参阅http://blogs.msmvps.com/jcoehoorn/blog/ 2014/05/12/can-we-stop-using-addwithvalue-already/ – Elliveny 2015-02-24 13:12:03

回答

1

代码你的意思是这样的?

SqlConnection sqlConn = new SqlConnection(connection string here); 
SqlCommand sqlComm = new SqlCommand(); 
sqlComm = sqlConn.CreateCommand(); 
sqlComm.CommandText = @"UPDATE User_tbl SET LastSeen=GetDate() WHERE UserName='@userName'"; 
sqlComm.Parameters.Add("@userName", SqlDbType.VarChar); 
sqlComm.Parameters["@userName"].Value = txtUserName.Text; 
sqlConn.Open(); 
sqlComm.ExecuteNonQuery(); 
sqlConn.Close(); 

您需要在'if(dt.Rows.Count> 0)'代码中沿着这些行放置某些内容。

您可能希望重用与您为SELECT语句创建的连接相同的连接。

许多其他选项可用。通常,使用存储过程可以最好地实现这种功能,在这种情况下,您可以检查登录凭据并在对数据库服务器的单个请求中执行任何相关更新。

+0

我想要这样。 如果(dt.Rows.Count> 0){ //这里写逻辑以更新与日期时间 的Response.Redirect( “default2.aspx”)LastSeen柱; } – 2015-02-24 13:51:24

+0

这是一个问题吗?如果是这样,是的,这是正确的。 – Elliveny 2015-02-24 13:55:24

+0

是的,这是问题..............对,但列仍然没有更新,错误也没有显示。 – 2015-02-24 14:07:45