首页 > 代码库 > 数据的导入

数据的导入

技术分享

string.Format("insert into {0}",hello);{0}就是一个占位符

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;

namespace _06文件导入
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Filter = "文本文件|*.txt";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    this.textBox1.Text = ofd.FileName;
                    //导入数据
                    ImportData(ofd.FileName);
                }
            }
        }
        private void ImportData(string fileName)
        {
            string temp = string.Empty;
            using (StreamReader reader = new StreamReader(fileName, Encoding.UTF8))
            {
                reader.ReadLine();//去掉第一行
                string constr = ConfigurationManager.ConnectionStrings["sql2"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                        con.Open();
                        while (!string.IsNullOrEmpty(temp = reader.ReadLine()))
                        {
                            //将字符串进行分割
                            var strs = temp.Split(,);
                            string sql = string.Format("insert into student(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 constr
                    
            }
        }
    }
}

配置文件的代码如下

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

 

数据的导入