Use Windows Forms to quickly/randomly insert large amounts of data into a database

Source: Internet
Author: User

     This article belongs to the class study note, the big God does not like to spray yo!!

today, this fast/random insert of large amounts of data into the database The example of a blog post is to randomly insert tens of thousands of messages into the database user Information table :

To create a Student information table in database studb:

CREATE TABLE Tblstudent
(
IntId int primary Key identity,
Chvstuname nvarchar () NOT NULL,--student name
Dtmbirthday datetime NOT NULL,--date of birth
Chvstuuid nvarchar () NOT NULL,--Social Security Number
Chvstuaddress nvarchar (+) NOT NULL,--home address
Chvstuphone nvarchar (one) not null--contact telephone

)
Go

  To create a project for a Windows Forms application:

  

Folder files in the three txt text is the student address and student's surname and name (the data inserted into the database are randomly generated according to the data in these three texts)

DataFactory write methods to auxiliary classes

public class DataFactory
{
<summary>
Define an array to hold the student's home address and name from the folder files match
</summary>
String[] Firstnames;
String[] Lastnames;
String[] shengs;
String[] Shis;

Public DataFactory ()
{
Extracting data from files in folders
String filePath = System.IO.Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "Files", "FirstName.txt");
Firstnames = System.IO.File.ReadAllText (FilePath). Split (new char[] {"}, stringsplitoptions.removeemptyentries);

FilePath = System.IO.Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "Files", "LastName.txt");
Lastnames = System.IO.File.ReadAllText (FilePath). Split (New char[]{'}, stringsplitoptions.removeemptyentries);

FilePath = System.IO.Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "Files", "Address.txt");
string[] Alllines = System.IO.File.ReadAllLines (FilePath);
Get the province of your address
Shengs = Alllines.where (item = Item). EndsWith ("Province")). ToArray ();
Get the city in your address
Shis = alllines.where (item =!shengs. Contains (item) && item. Length > 0). ToArray ();

}

<summary>
A method of randomly inserting large amounts of data into a database
</summary>
<param name= "Count" ></param>
<returns></returns>
Public list<tblstudent> getstudents (int count)
{
Ling to SQL connection string
Studbdatacontext dataContext = new Studbdatacontext ();
Student Information Sheet Collection
list<tblstudent> list = new list<tblstudent> ();
Random number
Random random = new random ();

Loop inserts the data to be generated into the database
while (list. Count<count)
{
Randomly generate student information data based on the number of data bars to be generated
for (int i = list. Count; I < count; i++)
{
Instantiate Student Information table
Tblstudent student = new Tblstudent ();
Randomly get the student's name
Student.chvstuname = Firstnames[random. Next (0, Firstnames.length)] + lastnames[random. Next (0, lastnames.length)];

Randomly get the student's ID number
String idcard = "";
while (Idcard. Length < 18)
{
Idcard + = random. Next (0, 10);
}
Student.chvstuuid = Idcard;

Randomly get a student's home address
Student.chvstuaddress = Shengs[random. Next (0, Shengs. Length)] + shis[random. Next (0, Shis. Length)];

Randomly get the student's phone number
string phone = "1";
while (phone. Length < 10)
{
Phone + = random. Next (0, 10);
}
Student.chvstuphone = phone;

Randomly get a student's date of birth
Student.dtmbirthday = DateTime.Parse (random. Next (1950, +) + "-" + random. Next (1, +) + "-" + random. Next (1, 28));
List. ADD (student);
}
/*************** determines that the generated ID number cannot be duplicated *******************/
Get all the generated ID numbers
string[] Allidcards = list. Select (Item=>item.chvstuuid). ToArray ();
Go to the database than the existing ID number
var hasidcards = dataContext.TblStudent.Where (item = allidcards.contains (Item.chvstuuid)). Select (item = item.chvstuuid). ToArray ();

List = list. Where (item =!hasidcards.contains (Item.chvstuuid)). ToList ();

}
return list;
}

}

Form Backend Code:

Namespace Bigdatagenerator
{

public partial class Form1:form
{
Public Form1 ()
{
InitializeComponent ();
}

public delegate void Changeuihandler (int count);

<summary>
Insert Data progress bar (method)
</summary>
<param name= "Progress" ></param>
public void Changeprogressbar (int progress)
{
This.progressBar1.Value = progress;
This.label2.Text = progress + "%";

}
The value of the button and text boxes can be used after the data is inserted successfully into the database (method)
public void changecontrolenabled (int data)
{
This.button1.Enabled = true;
This.textBox1.Enabled = true;

}

Inserting data into the database
private void Generate (object data)
{
Update progress bar
This. Invoke (New Changeuihandler (Changeprogressbar), 0);
int count = (int) data;
Studbdatacontext dataContext = new Studbdatacontext ();
Insert data directly into the database when the user inserts data <100 in the database
if (Count < 100)
{
Inserting data into the database
list<tblstudent> list = new DataFactory (). Getstudents (count);
DataContext.TblStudent.InsertAllOnSubmit (list);
Datacontext.submitchanges ();
Update progress bar
This. Invoke (New Changeuihandler (Changeprogressbar), 100);
}
If the user inserts data >=100 in the database, the thread executes it for the computer not to die.
Else
{
int countpertime = 100;
int times = (int) math.ceiling (count * 1.0/countpertime);

for (int i = 1; I <= times; i++)
{
list<tblstudent> list = new DataFactory (). Getstudents (Countpertime);
if (i = = times)
{
List = new DataFactory (). Getstudents (Countpertime + (Count-(Countpertime * (i-1)));
}
Inserting data into the database
DataContext.TblStudent.InsertAllOnSubmit (list);
Datacontext.submitchanges ();

Update the progress bar (thread-safe, ProgressBar is created by the UI thread, and the current code is executed by the newly created thread, so it is not secure.)

int progress = (int) ((i * 1.0/times) * 100);

This. Invoke (New Changeuihandler (Changeprogressbar), progress);

}

}
Update progress bar (revert to default state 0%)
This. Invoke (New Changeuihandler (changecontrolenabled), 0);

}

private void Button1_Click (object sender, EventArgs e)
{
int count = Int. Parse (This.textBox1.Text.Trim ());
Thread thread = new Thread (new Parameterizedthreadstart (Generate));
Thread. Start (count);
Before you insert data into the database, the button buttons and the values of the text boxes are not available
this.button1.Enabled = false;
this.textBox1.Enabled = false;

}
}
}

Operating effect:

Use Windows Forms to quickly/randomly insert large amounts of data into a database

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.