程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> asp.net下將純真IP數據導入數據庫中的代碼

asp.net下將純真IP數據導入數據庫中的代碼

編輯:ASP.NET基礎
純真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個小時左右!
寫入到數據庫後的截圖如下:
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved