轉載收藏,作者不詳了.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
///
/// 擷取IP資料資訊的類
///
public class IPControl
{
//常量用來表示T-SQL語句中用到的變數名稱
private const string PARM_IP_ADDRESS = "@IPAddress";
private const string PARM_IP_SRC = "@IPSrc";
private const string PARM_IP_DATETIME = "@IPDateTime";
//T-SQL語句
private const string SQL_INSERT_IPSTAT = "INSERT INTO IPStat VALUES(@IPAddress,@IPSrc,@IPDateTime)";
private const string SQL_DELETE_IPSTAT = "delete from IPStat WHERE DATEDIFF(d,ip_datetime,getdate())>30"; //只保留一個月的資料
private const string SQL_SELECT_TOTAL = "SELECT COUNT(*) FROM IPStat ";
private const string SQL_SELECT_TODAY = "SELECT COUNT(*) FROM IPStat WHERE DATEDIFF(d,ip_datetime,getdate())=0";
private const string SQL_SELECT_YESTERDAY = "SELECT COUNT(*) FROM IPStat WHERE DATEDIFF(d,ip_datetime,getdate())=1";
private const string SQL_SELECT_MONTH = "SELECT COUNT(*) FROM IPStat WHERE DATEDIFF(d,ip_datetime,getdate())<30 and DATEDIFF(mm,ip_datetime,getdate())=0";
public IPControl()
{
}
///
/// 儲存IP資料資訊到資料庫
///
ip地址
///
ip來源
///
ip訪問時間
public void AddIP(string ipAddress,string ipSrc,DateTime ipDatetime)
{
//構建串連語句字串
StringBuilder strSQL = new StringBuilder();
//建立表示QQ號的參數
SqlParameter[] parms = new SqlParameter[] { new SqlParameter(PARM_IP_ADDRESS, SqlDbType.NVarChar, 20),
new SqlParameter(PARM_IP_SRC, SqlDbType.NVarChar,80),
new SqlParameter(PARM_IP_DATETIME, SqlDbType.DateTime)};
SqlCommand cmd = new SqlCommand();
// 依次給參數賦值,並添加到執行語句中
parms[0].Value = ipAddress;
parms[1].Value = ipSrc;
parms[2].Value = ipDatetime;
foreach(SqlParameter parm in parms)
cmd.Parameters.Add(parm);
//定義對象資源儲存的範圍,一旦using範圍結束,將釋放對方所佔的資源
using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionStringLocalTransaction))
{
//在執行字串中載入插入語句
strSQL.Append(SQL_INSERT_IPSTAT);
conn.Open();
//設定SqlCommand的屬性
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSQL.ToString();
//執行SqlCommand命令
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
//如果執行成功,返回true,否則false。
}
}
public string GetTotal()
{
//調用SqlHelper訪問組件的方法返回第一行第一列的值
object count = SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_TOTAL, null);
//返回統計結果
return count.ToString();
}
public string GetToday()
{
//調用SqlHelper訪問組件的方法返回第一行第一列的值
object count = SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_TODAY, null);
//返回統計結果
return count.ToString();
}
public string GetYesterday()
{
//調用SqlHelper訪問組件的方法返回第一行第一列的值
object count = SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_YESTERDAY, null);
//返回統計結果
return count.ToString();
}
public string GetMonth()
{
//調用SqlHelper訪問組件的方法返回第一行第一列的值
object count = SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_MONTH, null);
//返回統計結果
return count.ToString();
}
}