用c#练习一个读取文件,导入数据库时,共两个字段,一个是UserName nvarchar(50)
一个是Age int;当是英文名字时,读取正常,是汉字时,就是乱码,郁闷呀。。
代码如下:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
return;
}
using (FileStream filestream = File.OpenRead(openFileDialog1.FileName))
{
using (StreamReader streamreader = new StreamReader(filestream))
{
using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "insert into T_usrs(name,age) values(@name,@age)";
string line = null;
while ((line = streamreader.ReadLine()) != null)
{
string[] lines = line.Split('|');
string name1 = lines[0];
int age = Convert.ToInt32(lines[1]);
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("name", name1));
cmd.Parameters.Add(new SqlParameter("age", age));
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("导入成功!");
}
}
}
} |