文件导入数据库操作

protected void Button1_Click(object sender, EventArgs e)
    {
        if (!FileUpload1.HasFile)
        {
            return;
           
        }
        using (FileStream filestream = File.OpenRead(FileUpload1.PostedFile.FileName))
        {
            using (StreamReader streamreader = new StreamReader(filestream))
            {
                //创建数据库耗时,所以不要每次操作都创建
                using (SqlConnection conn = new SqlConnection(@"Data Source=MS-201202131434\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True"))
                {
                    conn.Open();
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "insert into T_UserAge(Name,Age) values(@Name,@Age)";
                        string line = null;
                        while ((line = streamreader.ReadLine()) != null)
                        {
                            string[] strs = line.Split('|');
                            string name = strs[0];
                            int age = Convert.ToInt32(strs[1]);
                            cmd.Parameters.Clear();//参数不能重复添加,在一个while中用的都是一个SqlCommand对象   
                            cmd.Parameters.Add(new SqlParameter("Name", name));
                            cmd.Parameters.Add(new SqlParameter("Age", age));
                            cmd.ExecuteNonQuery();
                        }

                    }
                }
            }
        }

posted on 2012-03-13 12:32  张彦山  阅读(237)  评论(0编辑  收藏  举报