博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

txt文本导入到sql server数据库

Posted on 2008-11-07 11:33  hyd309  阅读(1378)  评论(2编辑  收藏  举报

 protected void Button1_Click(object sender, EventArgs e)
    {
        StreamReader sr = new StreamReader(new FileStream(@"C:\test.txt", FileMode.Open, FileAccess.Read), System.Text.Encoding.Default);

        SqlConnection cn = new SqlConnection("Server=server0.;uid=sa;pwd=1234;database=ISUZU"); ;

        string insertCmd = "insert into EPSubtute(Escmp,Esoem,Esrelation,Esnew,Espart,Essub) values (@Escmp,@Esoem,@Esrelation,@Esnew,@Espart,@Essub)";
          
        string strTemp = sr.ReadLine();
        while(strTemp != null)
        {           
            SqlCommand cmd =  new SqlCommand(insertCmd, cn);
           
            cmd.Parameters.Add("@Escmp", SqlDbType.VarChar).Value = "ISUZU";
            cmd.Parameters.Add("@Esoem", SqlDbType.VarChar).Value = "IZ";
            cmd.Parameters.Add("@Esrelation", SqlDbType.VarChar).Value =strTemp.Substring(0,2) ;
            cmd.Parameters.Add("@Esnew", SqlDbType.VarChar).Value = strTemp.Substring(2, 10);
            cmd.Parameters.Add("@Espart", SqlDbType.VarChar).Value = strTemp.Substring(12, 10);
            cmd.Parameters.Add("@Essub", SqlDbType.VarChar).Value = strTemp.Substring(22, 1);

            cn.Open();
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch(System.Data.SqlClient.SqlException e1)
            {
                Console.WriteLine(e1.Message);
            }
            cn.Close();
            strTemp = sr.ReadLine();
        }
        sr.Close();
    }