A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 王国文 中级黑马   /  2012-5-23 03:08  /  2752 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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


插入成功后,张三是乱码,英文的那一行正常

5 个回复

倒序浏览
看一下你数据库的编码是什么格式的,插入的数据和数据库的编码格式要一样的哦!
cmd.Parameters.Add(new SqlParameter("age",age));还有就是你不感觉你的这句话有问题吗。应该是这样的吧cmd.Parameters.Add(new SqlParameter("@age",age));
回复 使用道具 举报
朱亮辉 发表于 2012-5-23 09:15
看一下你数据库的编码是什么格式的,插入的数据和数据库的编码格式要一样的哦!
cmd.Parameters.Add(new Sq ...

是少了@,数据库的编码格式怎么看啊   后来我把txt的改成unicode,就没事了   
回复 使用道具 举报
USE master
DECLARE @Str sql_variant
SET @Str = (SELECT collationproperty('Chinese_PRC_Stroke_CI_AI_KS_WS', 'CodePage'))
BEGIN
IF @Str=936
  print '简体中文'
else if @Str=950
  print '繁体中文'
else if @Str=437
  print '美国/加拿大英语'
else if @Str=932
  print '日文'
else if @Str=949
  print '韩文'
else if @Str=866
  print '俄文'
else
print 'unicode UFT-8'
end

你把SQL 语句直接复制到SQL Server 中运行一下看输出的是什么编码格式的。
回复 使用道具 举报
可以把txt文件的格式转为uft-8编码,它默认为anst编码的。
回复 使用道具 举报
输出的数据是乱码无非是俩种情况: 一 数据库的问题 二 格式的问题
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马