txt文本导入到sql server数据库

 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();
    }

你可能感兴趣的:(SQL Server)