首页 > 代码库 > 数据的导入
数据的导入
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>
数据的导入
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。