program.cs文件:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace 数据导入导出
{
static class Program
{
///<sumary>
///应用程序的主入口点
///</summary>
[STAThread]
static void Main()
{
string dateDir = AppDomain.CurrentDomain.BaseDirectory;
if(dataDir.EndsWith(@"bin\Debug\")||dataDir.EndsWith(@"bin\Release\"))
{
dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
AppDomain.CurrentDomain.SetData("DataDirectory",dataDir);
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
数据导入导出.Form1文件:
using System;
using System.Collection.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 数据导入导出
{
public Form1()
{
InitializaComponent();
}
private void button1_Click(object sender,EventArgs e)
{
if(odfImport.ShowDialog() != DialogResult.OK)
{
return;
}
using(FileStream fileStream = File.OpenRead(odfImport.FileName))
{
using(StreamReaser streamReader = new StreamReader(fileStream))
{
using(SqlConnection conn = new SqlConnection(@"Data Source = .\SQLEXPRESS;AttachDBFilename=|DataDirectory|\MyDB.mdf;Integrated Security = True;User Instance = True"))
//创建连接是非常耗时的,因为不要每次操作都创建连接
{
conn.Open();
using(SqlCommand cmd = conn.CreateCommand())
{
string lines = null;
while(line = streamReader.ReadLine())! = null)
{
string[] strs = line.Split("|");
string name = strs[0];
int age = Convert.ToInt32(strs[1]);
cmd.Parameters.Clear();//!!!!参数不能重复添加,在while中一直用的就是一个SqlCommand对象
cmd.Parameters.Add(new SqlParameter("Name",name));
cmd.Parameters.Add(new SqlParameter("Age",name));
cmd.ExecuteNonQuery();
}
}
}
}
MessageBox.Show("导入成功!");
}
/*
if( odfImport.ShowDialog() == DialogResult.OK)
{
using(FileStream fileStream = File.OpenRead(odfImport.FileName))
{
using(StreamReaser streamReader = new StreamReader(fileStream))
{
string line = null;
while((line = streamReader.ReadLine())! = null)
{
string[] strs = line.Split('|');
string name = strs[0];
int age = Convert.ToInt32(strs[1]);
using(SqlConnection conn = new SqlConnection(@"Data Source = .\SQLEXPRESS;AttachDBFilename=|DataDirectory|\MyDB.mdf;Integrated Security = True;User Instance = True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Insert into T_Person(Name,Age) values(@Name,@Age)";
cmd.Parameters.Add(new SqlParameter("Name",name));
cmd.Parameters.Add(new SqlParameter("Age",name));
cmd.ExecuteNonQuery();
}
}
}
}
}
MessageBox.Show("导入成功!");
}*/
}
} |