在我的项目中,我想自动删除在45天内保持不活动状态的帐户。出于测试目的,我花了2分钟编写了以下代码。但它不起作用。如果保持不活动2分钟,任何人都可以告诉我如何执行“记录删除”。
我的代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Odbc;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=inactive;" + "UID=root;" + "PASSWORD=*********;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
try
{
MyConnection.Open();
OdbcCommand cmd = new OdbcCommand("DELETE name FROM email WHERE date < DATE_SUB(NOW(), INTERVAL 2 MIN)", MyConnection);
MyConnection.Close();
Label1.Text = "Done";
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=inactive;" + "UID=root;" + "PASSWORD=*********;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
try
{
MyConnection.Open();
OdbcCommand cmd = new OdbcCommand("Select name from email where email=?", MyConnection);
cmd.Parameters.Add("@email", OdbcType.VarChar, 255).Value = TextBox1.Text;
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
throw new Exception();
}
if (dr.Read())
{
Response.Write(dr[0].ToString());
}
}
catch
{
}
}
}
更新:
首先,我创建了一个名为inactive
的数据库,并创建了一个表email
。下面的屏幕截图显示了记录。
后来我使用了以下代码..
protected void Page_Load(object sender, EventArgs e)
{
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=inactive;" + "UID=root;" + "PASSWORD=******;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
try
{
MyConnection.Open();
OdbcCommand cmd = new OdbcCommand("DELETE FROM email WHERE `date` < DATE_SUB(NOW(), INTERVAL 2 MINUTE)", MyConnection);
MyConnection.Close();
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
答案 0 :(得分:1)
您需要在查询中添加date
,如下所示:
"DELETE FROM email WHERE `date` < DATE_SUB(NOW(), INTERVAL 2 MINUTE)"
当然,不为字段date
命名会更好,但更像lastchange
更具描述性。
答案 1 :(得分:1)
您的DELETE
语法似乎有误,请删除字段名称“name”,即
DELETE FROM email WHERE `date` < DATE_SUB(NOW(), INTERVAL 2 MINUTE)
(delete
命令删除整行,而不是单个字段)
答案 2 :(得分:1)
而不是 MIN ,您应该使用 MINUTE ,所以:
DELETE FROM email WHERE `date` < DATE_SUB(NOW(), INTERVAL 2 MINUTE)