美文网首页
C#从文本文件导入数据到数据库中

C#从文本文件导入数据到数据库中

作者: 幻凌风 | 来源:发表于2017-08-10 00:11 被阅读486次

    首先,通过SQL语句创建数据库Student,数据表名称为TableStudent

    CREATE DATABASE Sutdent;
    USE Student;
    CREATE TABLE TableStudent
    (
        stuId INT PRIMARY KEY IDENTITY(1,1) NOT NULL,
        stuName NVARCHAR(32) NULL,
        stuSex NCHAR NULL,
        stuBirthdate NVARCHAR(32) NULL,
        stuPhone NVARCHAR(32) NULL,
    );
    

    其次,准备Data.txt文本文件数据

    stuId,stuName,stuSex,stuBirthdate,stuPhone
    1,龙公子,f,1980-01-01 00:00:00.000,12345678909
    2,苏坤,m,1979-11-21 00:00:00.000,12345678908
    3,马伦,m,1982-02-14 00:00:00.000,12345678907
    4,王成伟,m,1984-07-11 00:00:00.000,12345678906
    5,牛亮亮,m,1977-09-17 00:00:00.000,12345678905
    6,令狐冲,m,1989-03-01 00:00:00.000,12345678904
    7,DN老毕,m,1986-06-23 00:00:00.000,12345678903
    8,柴静,f,1990-05-20 00:00:00.000,12345678902
    9,沙尘暴,f,NULL,12345678901
    10,老逼养的,m,1988-07-21 00:00:00.000,NULL
    11,刘翔,NULL,1981-11-06 00:00:00.000,12345678999
    

    再次,应用程序配置文件中配置数据库连接字符串

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <connectionStrings>
        <add name="strConnect" connectionString="server=127.0.0.1;uid=sa;pwd=123456;database=Student"/>
      </connectionStrings>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
        </startup>
    </configuration>
    

    最后,代码如下

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO;
    using System.Data.SqlClient;
    using System.Configuration;//该命名空间需要引入程序集System.Configuration
    
    namespace DataImportExample
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void ImportData(string fileName)
            {
                string temp = string.Empty;
                using (StreamReader reader = new StreamReader(fileName, Encoding.UTF8))
                {
                    reader.ReadLine();
                    //数据库连接字符串
                    //string strConnect = "server=localhost;uid=sa;pwd=YUNWEN0305;database=Student";
                    string strConnect = ConfigurationManager.ConnectionStrings["strConnect"].ConnectionString;
                    using (SqlConnection conn = new SqlConnection(strConnect))
                    {
                        conn.Open();
                        using (SqlCommand cmd = conn.CreateCommand())
                        {
                            while (!string.IsNullOrEmpty(temp = reader.ReadLine()))
                            {
                                //把字符串进行分隔然后生成一条SQL语句插入到数据库中去
                                var strs = temp.Split(',');
                                string sql = string.Format(@"insert into TableStudent (stuName,stuSex,stuBirthdate,stuPhone) values ('{0}','{1}','{2}','{3}')",strs[1],strs[2],strs[3],strs[4]);
    
                                cmd.CommandText = sql;
                                cmd.ExecuteNonQuery();
                            }//end while
                        }//end using cmd
                    }//end using conn
                }//end using reader
            }
    
            private void btnImport_Click(object sender, EventArgs e)
            {
                using (OpenFileDialog ofd = new OpenFileDialog())
                {
    
                    ofd.Filter = "文件文件|*.txt";
                    if (ofd.ShowDialog() == DialogResult.OK)
                    {
                        this.textBoxFilePath.Text = ofd.FileName;
                        //导入数据工作
                        ImportData(ofd.FileName);
                        MessageBox.Show("OK");
                    }
                }
            }
        }
    }
    

    运行效果

    运行效果.png

    数据库

    数据库.png

    相关文章

      网友评论

          本文标题:C#从文本文件导入数据到数据库中

          本文链接:https://www.haomeiwen.com/subject/ukdcrxtx.html