首页 > 代码库 > 数据导入

数据导入

//做数据导入工作
        private void ImportData(string fileName)
        {
            string temp = string.Empty;
            //第一步:拿到文件
            //File.ReadAllLines();
            using (StreamReader reader = new StreamReader(fileName, Encoding.UTF8))
            {
                reader.ReadLine();//去掉第一行。
                string connStr = ConfigurationManager.ConnectionStrings["sqlConn"].ConnectionString;

                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        conn.Open();//连接只能打开一次。
                        while (!string.IsNullOrEmpty(temp = reader.ReadLine()))
                        {
                            //把字符串进行分割然后生成一条sql插入到数据库中去。
                            var strs = temp.Split(‘,‘);
                            string sql = string.Format(@"
                     insert into tblStudent
                     (stuName,stuSex,stuBirthDate,stuPhone)
                     values(‘{0}‘,‘{1}‘,‘{2}‘,‘{3}‘)", strs[1], strs[2], strs[3], strs[4]);
                            cmd.CommandText = sql;
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
            }

数据:StreamReader reader = new StreamReader(fileName, Encoding.UTF8), reader.ReadLine();//去掉第一行,这样就可以去掉第一行我们不需要的数据

stuId,stuName,stuSex,stuBirthdate,stuPhone
1,龙公子,f,1980-01-01 00:00:00.000,12345678909
2,苏坤,m,1979-11-21 00:00:00.000,12345678908
3,马伦,m,1982-02-14 00:00:00.000,12345678907
4,王成伟,m,1984-07-11 00:00:00.000,12345678906
5,牛亮亮,m,1977-09-17 00:00:00.000,12345678905
6,令狐冲,m,1989-03-01 00:00:00.000,12345678904
7,DN老毕,m,1986-06-23 00:00:00.000,12345678903
8,柴静,f,1990-05-20 00:00:00.000,12345678902
9,沙尘暴,f,NULL,12345678901
10,老逼养的,m,1988-07-21 00:00:00.000,NULL
11,刘翔,NULL,1981-11-06 00:00:00.000,12345678999

数据导入