日期:2014-05-17  浏览次数:20816 次

C#从txt文档导入到SQLServer数据库表出现乱码
C# code

//文件导入
        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            using (FileStream fileStream = File.OpenRead(openFileDialog1.FileName))
            {
                using (StreamReader streamReader = new StreamReader(fileStream))
                {
                    using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\C#工作文件夹\TestDemo\文件导入导出\文件导入导出\Database1.mdf;Integrated Security=True;User Instance=True"))
                    {
                        conn.Open();
                        using (SqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = "insert into T_xiaoli (Name,Num) values (@Name,@Num)";
                            string line = "";
                            while ((line = streamReader.ReadLine()) != null)
                            {
                                string[] str = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                                string name = str[0];
                                int num = Convert.ToInt32(str[1]);
                                cmd.Parameters.Clear();//将cmd的参数清空,避免参数重复追加到尾,出错
                                cmd.Parameters.Add(new SqlParameter("Name", name));
                                cmd.Parameters.Add(new SqlParameter("Num", num));
                                cmd.ExecuteNonQuery();
                            }
                        }
                    }
                }
            }
            MessageBox.Show("导入成功!");
        }



代码如上,一切正常,就是导入成功后,txt文档里的内容在表中显出不出来,咋处理?
txt文档内容:
1xiaoli 9627
2小黎 3804
3Aaron 72335
4Aaron黎 3549

在数据库表中变成了:
1xiaoli 9627
2С?? 3804
3Aaron 72335
4Aaron?? 3549

数据库表的字段类型:
Name nvarchar(50)
Num int

------解决方案--------------------
中文的格式是Unicode,UTF-8,为什么把txt文件存到数据库呢,把txt文件里的内容读出来存进去不更方便吗?
------解决方案--------------------
using (StreamReader streamReader = new StreamReader(fileStream))
不加编码参数,读出来的就可能是乱码???