您的位置:首页 > 数据库

C#批量导入text到数据库sqlserver

2013-09-24 16:54 190 查看
using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System;

using System.Data;

using System.Data.SqlClient;

using System.IO;

namespace WindowsFormsApplication1

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

this.label1.Text = loadData().ToString();

}

public string randStr(int count)

{

string allchar = "1,2,3,4,5,6,7,8,9,0";

string[] allchararray = allchar.Split(',');

string randomcode = "";

int temp = -1;

Random rand = new Random();

for (int i = 0; i < count; i++)

{

if (temp != -1)

{

rand = new Random(i * temp * ((int)DateTime.Now.Ticks));

}

int t = rand.Next(10);

if (temp == t)

{

return randStr(count);

}

temp = t;

randomcode += allchararray[t];

}

return randomcode;

}

public int loadData()

{

StreamReader sr = new StreamReader(new FileStream("data.txt", FileMode.Open, FileAccess.Read), System.Text.Encoding.Default);

SqlConnection cn = new SqlConnection("Server=.;uid=sa;pwd=1122;database=vehicle"); ;

string insertCmd = "insert into infovehicle(Vehiclenum,vehicleid,sim) values (@Vehiclenum,@id, @sim)";

char delimChar = '\t';

string[] split = null;

int count = 0;

string strTemp = sr.ReadLine();

string strName=null;

string err="";

while (strTemp != null)

{

split = strTemp.Split(delimChar);

SqlCommand cmd = new SqlCommand(insertCmd, cn);

count++;

strName ="V"+ DateTime.Now.ToString("yyyyMMddhhmmss").ToString()+randStr(4);

string temp1 = split[0].ToString();

string temp2 =split[1].ToString().ToString();

string temp3 = split[2].ToString().ToString();

cmd.Parameters.Add("@Vehiclenum", SqlDbType.VarChar).Value = strName;

cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = split[0];

cmd.Parameters.Add("@sim", SqlDbType.VarChar).Value = split[2];

cn.Open();

try

{

cmd.ExecuteNonQuery();

}

catch (System.Data.SqlClient.SqlException e)

{

Console.WriteLine(e.Message);

err += int.Parse(count.ToString()).ToString() + "#";

}

cn.Close();

strTemp = sr.ReadLine();

}

sr.Close();

err = err;

return count;

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: