Import pure IP data into the database code in asp.net

Source: Internet
Author: User

There are 381085 pieces of pure IP data. You can decompress the data into text format by downloading the query software and change the encoding to UTF8. Otherwise, Chinese characters will be garbled in the program!
The following code analyzes IP data and inserts it into SQL Server:



The program inserts data in the client through AJAX for real-time update:
The implementation code is as follows:
Front-end page and javascript:
Copy codeThe Code is as follows:
<! 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/5o/xhtml">
<Head>
<Title> import the IP address database-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; // The total number of IP records.
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.css Text = "display: none ";
Document. body. appendChild (elem );
Document.forms%0%.tar get = elem. name;
}
Document. forms [0]. submit ();
Log. innerHTML = "uploading data! <Br/> ";
Return false;
}
��
Function insertIP (){
Log. innerHTML + = "start to analyze data... <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> data analysis succeeded: <br/> server address:" +
D. server + ", record:" + recordCount +! <Br/> <div id = 'recordlog'> </div> ";
// Start inserting
Insert ();
},
Function (x) {log. innerHTML + = "<font color = red> An exception occurred and ended! </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 = "data written:" + (recordCount-d.count) +
", Queue:" + d. count + ", this write:" + d. insertNum + ";
If (d. count! = 0) {insert ();}
Else {reLog. innerHTML = "congratulations, writing is complete !";}
}, Function (x) {alert (x );});
}
</Script>
</Head>
<Body>
<Div style = "margin: 60px 100px">
<Div id = "log"> enter relevant data and select an IP data file! </Div>
<Form action = "/do. ashx? Args = ImportIPData "method =" post "enctype =" multipart/form-data "target =" ifr ">
Database IP address: <input type = "text" name = "dbserver" value = "."/> <br/>
Database name: <input type = "text" name = "dbname" value = "tp"/> <br/>
Data Table name: <input type = "text" name = "tbname" value = "ip"/> <br/>
User name: <input type = "text" name = "dbuid" value = "sa"/> <br/>
Password <input type = "password" name = "dbpwd" value = "123000"/> <br/>
IP file: <input type = "file" name = "ipfile" value = "C: \ Users \ cwliu \ Desktop \ 1.txt"/> <br/>
<Button onclick = "return startImport ();"> Import </button>
</Form>
</Div>
</Body>
</Html>

Note: j is a custom javascript class library, which contains the ajax function code.
The background program is used to receive Post requests sent by ajax:
The Code is as follows:
Copy codeThe Code is as follows:
File: do. ashx? Args = ImportIPData
Public void ProcessRequest (HttpContext context)
{
If (context. Request. RequestType = "POST ")
{
String action = context. Request ["action"];
// Submit IP data
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"]);
// Save the database connection string and data table name
HttpContext. Current. Session ["ip_dbconnstring"] = sb. ToString ();
HttpContext. Current. Session ["ip_tablename"] = tbname;
// Read IP data and cache it
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 );
// Send data to the client (in Json format)
Sb. Remove (0, sb. Length );
Sb. Append ("[{server: '"). Append (dbserver) // server address
. Append ("', count:'"). Append (ipList. Count) // number of IP entries
. Append ("', insertNum: 0") // Number of inserted items
. Append (", taskNum: 0") // number of task queues
. Append ("}]");
Context. Session ["ip_info"] = sb. ToString ();
// Trigger the parent page to start inserting data
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;
// Initialize, create a table, and return information
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 (), 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"]);
}
// Insert data
Else if (action = "insert ")
{
IList <string> ipList = HttpRuntime. Cache ["ip_data"] as IList <string>;
StringBuilder sb = new StringBuilder (400 );
// By default, 300 entries are inserted each time.
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) // number of IP entries not inserted
. Append (", insertNum:"). Append (insertNum)
. Append ("}]");
Context. Response. Write (sb. ToString ());
}
}
}
}
}
}

After the above Code is processed, IP data will be added to your database! The total number is 0.38 million. The time for adding is about 1 hour!
The data written to the database is as follows:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.