asp.net下將純真IP資料匯入資料庫中的代碼

來源:互聯網
上載者:User

純真IP資料包含381085條,可以通過下載的查詢軟體將資料解壓為文字格式設定,並將其編碼改為UTF8,否則在程式中讀取中文會亂碼!
下面為程式執行分析IP資料並插入到Sql Server的:


程式通過AJAX在用戶端進行資料插入即時更新:
實現代碼如下:
前端頁面及javascript: 複製代碼 代碼如下:<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head>
<title>匯入IP地址資料庫-power by blog.atnet.cc</title>
<style type=”text/css”>
body{font-size:14px;}
#log{border:solid 1px gold;width:400px;height:100px;padding:10px;background:gold;margin-bottom:15px;color:black;}
#recordLog{font-size:12px;}
</style>
<script type=”text/javascript” src=”/scripts/global.js”></script>
<script type=”text/javascript”>
var log,reLog; //Log,RecordLog
var recordCount; //IP記錄總數
window.onload=function(){
log=document.getElementById(“log”);
}
function startImport(){
if(!document.getElementById(“submit_ifr”)){
var elem=document.createElement(“iframe”);
elem.setAttribute(“id”,”submit_ifr”);
elem.setAttribute(“name”,”ifr”);
elem.style.cssText=”display:none”;
document.body.appendChild(elem);
document.forms[0].target=elem.name;
}
document.forms[0].submit();
log.innerHTML=”正在上傳資料!<br />”;
return false;
}

function insertIP(){
log.innerHTML+=”開始分析資料…<br />”;
j.ajax.post(“/do.ashx?args=ImportIPData&action=init”,”",
function(x){
var d=eval(x)[0];
recordCount=d.count;
log.innerHTML+=”<font color=green>分析資料成功:<br />伺服器位址:”+
d.server+”,記錄:”+recordCount+”條!<br /><div id='recordLog'></div>”;
//開始插入
insert();
},
function(x){log.innerHTML+=”<font color=red>發生異常,已終止!</font>”;}
);
}
function insert(){
if(!reLog)reLog=document.getElementById(“recordLog”);
var num=Math.floor(Math.random()*100);
j.ajax.post(“/do.ashx?args=ImportIPData&action=insert”,”num=”+num,
function(x){var d=eval(x)[0];reLog.innerHTML=”已經寫入資料:”+(recordCount-d.count)+
“條,隊列:”+d.count+”條,本次寫入:”+d.insertNum+”條”;
if(d.count!=0){insert();}
else{reLog.innerHTML=”恭喜,寫入完畢!”;}
},function(x){alert(x);});
}
</script>
</head>
<body>
<div style=”margin:60px 100px”>
<div id=”log”>請填寫相關資料,選擇IP資料檔案!</div>
<form action=”/do.ashx?args=ImportIPData” method=”post” enctype=”multipart/form-data” target=”ifr”>
資料庫IP:<input type=”text” name=”dbserver” value=”.” /><br />
資料庫名:<input type=”text” name=”dbname” value=”tp” /><br />
資料表名:<input type=”text” name=”tbname” value=”ip” /><br />
用 戶 名:<input type=”text” name=”dbuid” value=”sa” /><br />
密 碼<input type=”password” name=”dbpwd” value=”123000″ /><br />
IP檔案:<input type=”file” name=”ipfile” value=”C:\Users\cwliu\Desktop\1.txt” /><br />
<button onclick=”return startImport();”>匯入</button>
</form>
</div>
</body>
</html>

注:j為一個自訂的javascript類庫,中間包含了ajax功能的代碼
背景程式我們用來接收ajax發送的Post 請求:
代碼如下: 複製代碼 代碼如下:File:do.ashx?args=ImportIPData
public void ProcessRequest(HttpContext context)
{
if (context.Request.RequestType == “POST”)
{
string action = context.Request["action"];
//提交IP資料
if (string.IsNullOrEmpty(action) || action == “submit”)
{
string dbserver = context.Request["dbserver"], tbname = context.Request["tbname"];
StringBuilder sb = new StringBuilder(500);
sb.Append(“server=”).Append(dbserver).Append(“;database=”).Append(context.Request["dbname"])
.Append(“;uid=”).Append(context.Request["dbuid"]).Append(“;pwd=”).Append(context.Request["dbpwd"]);
//儲存資料庫連接字串及資料表名
HttpContext.Current.Session["ip_dbconnstring"] = sb.ToString();
HttpContext.Current.Session["ip_tablename"] = tbname;
//讀取IP資料並緩衝
IList<string> ipList = new List<string>();
HttpPostedFile file = context.Request.Files[0];
using (StreamReader sr = new StreamReader(file.InputStream, Encoding.UTF8))
{
while (sr.Peek() != -1)
{
ipList.Add(Regex.Replace(sr.ReadLine(), “\\s{2,}”, ” “));
}
}
HttpRuntime.Cache.Insert(“ip_data”, ipList);
//想用戶端發送資料資訊(Json格式)
sb.Remove(0, sb.Length);
sb.Append(“[{server:'").Append(dbserver) //伺服器位址
.Append("',count:'").Append(ipList.Count) //IP條數
.Append("',insertNum:0") //本次插入條數
.Append(",taskNum:0") //任務隊列條數
.Append("}]“);
context.Session["ip_info"] = sb.ToString();
//觸發父頁面開始插入資料
context.Response.Write(“<script>window.parent.insertIP();</script>”);
}
else
{
using (SqlConnection conn = new SqlConnection(context.Session["ip_dbconnstring"] as string))
{
string tbname = context.Session["ip_tablename"] as string;
//初始化,建表並返回資訊
if (action == “init”)
{
SqlCommand cmd = new SqlCommand(“if not exists(select * from sysobjects where [name]='” + tbname +
“‘ and xtype='u')BEGIN CREATE TABLE ” + tbname + “(id BIGINT PRIMARY KEY IDENTITY(1,1),sip NVARCHAR(15),eip NVARCHAR(15),area NVARCHAR(80),[name] NVARCHAR(80))END”, conn);
conn.Open();
cmd.ExecuteNonQuery();
context.Response.Write(context.Session["ip_info"]);
}
//插入資料
else if (action == “insert”)
{
IList<string> ipList = HttpRuntime.Cache["ip_data"] as IList<string>;
StringBuilder sb = new StringBuilder(400);
//預設每次插入300條
int insertNum;
int.TryParse(context.Request["num"], out insertNum);
if (insertNum < 1) insertNum = 300;
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddRange(
new SqlParameter[]{
new SqlParameter(“@sip”,null),
new SqlParameter(“@eip”,null),
new SqlParameter(“@area”,null),
new SqlParameter(“@name”,null)
});
cmd.Connection = conn;
conn.Open();
string[] arr;
for (var i = 0; i <= insertNum && i < ipList.Count; i++)
{
arr = ipList[i].Split(‘ ‘);
cmd.CommandText = “if not exists(select id from ” + tbname +
” where sip='”+arr[0]+”‘and eip='”+arr[1]+”‘) INSERT INTO ” + tbname +
” values(@sip,@eip,@area,@name)”;
cmd.Parameters["@sip"].Value = arr[0];
cmd.Parameters["@eip"].Value = arr[1];
cmd.Parameters["@area"].Value = arr[2];
cmd.Parameters["@name"].Value =arr.Length>=4?arr[3]:”";
sb.Remove(0, sb.Length);
cmd.ExecuteNonQuery();
ipList.Remove(ipList[i]);
}
sb.Remove(0, sb.Length);
sb.Append(“[{count:").Append(ipList.Count) //未插入IP的條數
.Append(",insertNum:").Append(insertNum)
.Append("}]“);
context.Response.Write(sb.ToString());
}
}
}
}
}
}

當處理上面的代碼之後IP資料將添加到你的資料庫中!總數是38萬條添加時間在1個小時左右!
寫入到資料庫後的如下:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.