码迷,mamicode.com
首页 > 其他好文 > 详细

数据的导入

时间:2017-03-15 00:20:10      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:null   names   uname   text   blog   birt   ace   rem   runtime   

技术分享

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>

 

数据的导入

标签:null   names   uname   text   blog   birt   ace   rem   runtime   

原文地址:http://www.cnblogs.com/lili-work/p/6551360.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!