TXT导入数据到SQL

来源:互联网 发布:期货套利分析软件 编辑:程序博客网 时间:2024/04/30 21:01
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();        }    }}
0 0
原创粉丝点击