標籤:des style color io os ar 使用 for strong
本文屬於上課學習筆記,各位大神不喜勿噴喲!!
今天寫的這個快速/隨機的向資料庫插入大量資料的博文的例子是向資料庫使用者資訊表中隨機插入上萬條資訊:
在資料庫StuDB中建立學生資訊表:
create table TblStudent
(
intId int primary key identity,
chvStuName nvarchar(20) not null,--學生名稱
dtmBirthday datetime not null,--出生日期
chvStuUid nvarchar(18) not null,--社會安全號碼
chvStuAddress nvarchar(30) not null,--家庭住址
chvStuPhone nvarchar(11) not null--聯絡電話
)
go
建立Windows表單應用程式的項目:
檔案夾Files裡的三個txt文本分別裝的是學生住址與學生的姓與名(後面插入到資料庫的資料均是根據這三個文本裡的資料隨機產生的)
向輔助類DataFactory寫入方法
public class DataFactory
{
/// <summary>
/// 定義數組存放從檔案夾Files匹配的學生的家庭住址與姓名
/// </summary>
string[] firstNames;
string[] lastNames;
string[] shengs;
string[] shis;
public DataFactory()
{
//從檔案夾Files裡取出資料
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);
//得到住址中的省
shengs = allLines.Where(item => item.EndsWith("省")).ToArray();
//得到住址中的市
shis = allLines.Where(item => !shengs.Contains(item) && item.Length > 0).ToArray();
}
/// <summary>
/// 隨機向資料庫插入大量的資料的方法
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public List<TblStudent> GetStudents(int count)
{
//ling to sql連接字串
StuDBDataContext dataContext = new StuDBDataContext();
//學生資訊表集合
List<TblStudent> list = new List<TblStudent>();
//Random隨機數
Random random = new Random();
//迴圈向資料庫中插入要產生的資料
while (list.Count<count)
{
//根據要產生的資料條數迴圈隨機產生學生資訊資料
for (int i = list.Count; i < count; i++)
{
//執行個體化學生資訊表
TblStudent student = new TblStudent();
//隨機得到學生的姓名
student.chvStuName = firstNames[random.Next(0, firstNames.Length)] + lastNames[random.Next(0, lastNames.Length)];
//隨機得到學生的社會安全號碼
string idcard = "";
while (idcard.Length < 18)
{
idcard += random.Next(0, 10);
}
student.chvStuUid = idcard;
//隨機得到學生的家庭住址
student.chvStuAddress = shengs[random.Next(0, shengs.Length)] + shis[random.Next(0, shis.Length)];
//隨機得到學生的電話號碼
string phone = "1";
while (phone.Length < 10)
{
phone += random.Next(0, 10);
}
student.chvStuPhone = phone;
//隨機得到學生的出生日期
student.dtmBirthday = DateTime.Parse(random.Next(1950, 2000) + "-" + random.Next(1, 13) + "-" + random.Next(1, 28));
list.Add(student);
}
/***************判斷產生的社會安全號碼不能重複*******************/
//擷取所有產生的社會安全號碼
string[] allIdCards = list.Select(item=>item.chvStuUid).ToArray();
//去資料庫比對已經存在的社會安全號碼
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;
}
}
表單後台代碼:
namespace BigDataGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public delegate void ChangeUIHandler(int count);
/// <summary>
/// 插入資料進度條(方法)
/// </summary>
/// <param name="progress"></param>
public void ChangeProgressBar(int progress)
{
this.progressBar1.Value = progress;
this.label2.Text = progress + "%";
}
//向資料庫插入資料成功後button按鈕和文字框的值可以使用(方法)
public void ChangeControlEnabled(int data)
{
this.button1.Enabled = true;
this.textBox1.Enabled = true;
}
//向資料庫中插入資料
private void Generate(object data)
{
//更新進度條
this.Invoke(new ChangeUIHandler(ChangeProgressBar), 0);
int count = (int)data;
StuDBDataContext dataContext = new StuDBDataContext();
//如果使用者插入資料庫中的資料<100時,就直接向資料庫中插入資料
if (count < 100)
{
//向資料庫中插入資料
List<TblStudent> list = new DataFactory().GetStudents(count);
dataContext.TblStudent.InsertAllOnSubmit(list);
dataContext.SubmitChanges();
//更新進度條
this.Invoke(new ChangeUIHandler(ChangeProgressBar), 100);
}
//如果使用者插入資料庫中的資料>=100時,為了電腦不會卡死,就用線程執行
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))));
}
//向資料庫中插入資料
dataContext.TblStudent.InsertAllOnSubmit(list);
dataContext.SubmitChanges();
//更新進度條(安全執行緒,progressBar是由UI線程建立,而當前代碼是被新建立的線程執行的,所以是不安全的.)
int progress = (int)((i * 1.0 / times) * 100);
this.Invoke(new ChangeUIHandler(ChangeProgressBar), progress);
}
}
//更新進度條(恢複成預設狀態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);
//向資料庫插入資料成功前button按鈕和文字框的值不可以使用
this.button1.Enabled = false;
this.textBox1.Enabled = false;
}
}
}
運行效果:
利用Windows表單快速/隨機的向資料庫插入大量資料