TXT导入数据到SQL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
namespace _03导入数据
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "Data Source=XY-PC;Initial Catalog=MyItcast;Integrated Security=True";
            using (StreamReader reader=new StreamReader("333.txt"))
            {
                string line= reader.ReadLine();//第一行列名读完了,不要了
                using (SqlConnection con=new SqlConnection(str))
                {
                    con.Open();
                    string sql = "insert into UserLogin values(@UserName, @UserPwd)";
                    SqlParameter[] ps = {
                                            //告诉数据库 我的参数中存的值要以nvarchar类型存到表中
                                          new SqlParameter("@UserName", System.Data.SqlDbType.NVarChar),
                                          new SqlParameter("@UserPwd", System.Data.SqlDbType.VarChar)
                                        };
                    using (SqlCommand cmd=new SqlCommand(sql,con))
                    {
                        cmd.Parameters.AddRange(ps);//因为第一行是列名,只读取一次,所以不放入while循环
                        while ((line = reader.ReadLine()) != null)
                        {
                            string[] txts = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            //把参数用什么值替换
                            ps[0].Value = txts[1];//名字,填到语句里string sql = "insert into UserLogin values(@UserName, @UserPwd)"; txts[0]是ID,是逻辑主键标识,舍弃掉
                            ps[1].Value = txts[2];
                            cmd.ExecuteNonQuery();//循环执行SQL语句 string sql = "insert into UserLogin values(@UserName, @UserPwd)";  
                        }                       
                    }
                }

            }
            Console.WriteLine("学好挖掘机控制计算机成为卡帕斯基");
            Console.ReadKey();
        }
    }
}

 

posted @ 2016-11-12 15:00  影落明湖  阅读(1090)  评论(0编辑  收藏  举报