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.IO;
using System.Data.SqlClient;
namespace 导入
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static string str = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
private void button1_Click(object sender, EventArgs e)
{
if (ofdImport.ShowDialog()!=DialogResult.OK)
{
return;
}
using (FileStream fileStream =File.OpenRead(ofdImport.FileName))
{
using (StreamReader stringreader = new StreamReader(fileStream))
{
string line = null;
while ((line = stringreader.ReadLine()) != null)
{
string[] strs = line.Split('|');
string name = strs[0];
int age = Convert.ToInt32(strs[1]);
using (SqlConnection con = new SqlConnection(str))
{
con.Open();
using (SqlCommand cmd =con.CreateCommand())
{
cmd.CommandText = "insert into T_persons (name,age) values (@name,@age)";
cmd.Parameters.Add(new SqlParameter("@name", name));
cmd.Parameters.Add(new SqlParameter("age",age));
cmd.ExecuteNonQuery();
}
}
}
}
}
}
}
}
name age
lilei | 25
张三 | 21
插入成功后,张三是乱码,英文的那一行正常 |
|