C#文本文件导入数据库

时间:2024-12-05 23:06:49

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using Microsoft.Win32;
using System.Data.SqlClient;

namespace 手机号码归属地查询
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

private void button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter="文本文件|*.txt";
            if(ofd.ShowDialog()!=true)
            {
                return;
            }
            //IEnumerable<string> lines = File.ReadLines(ofd.FileName, Encoding.Default);
            string[] lines = File.ReadLines(ofd.FileName, Encoding.Default).ToArray();
                        for (int i = 1; i < lines.Count();i++ )
            {
                 string line =lines[i];

string[] segs= line.Split('\t'); //注意文件文本的分割方式
                string startTelNum=segs[0];
                string city = segs[1];
                city = city.Trim('"');
                string teltye= segs[2];
                teltye = teltye.Trim('"');
                SqlHelper.ExcuteNonQuery("insert into T_tel (StartNum ,TelArea,TelType) values ('" + startTelNum + "','" + city + "','" + teltye + "')");
                //SqlHelper.ExcuteNonQuery("insert into T_tel (StartNum ,TelArea,TelType) values (@startnum,@telarea,@teltype)",
                //    new SqlParameter("@startnum", startTelNum),
                //    new SqlParameter("@telarea", city),
                //    new SqlParameter("@teltype", teltye));
            }
            MessageBox.Show("导入成功!");
        }
    }

}

  此方法效率低下,耗时长,仅为学习!