
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace 文件导入导出
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnImport_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)//左边bool值,右边枚举型,怎么能够相等?
{
//FileStream fileStream = File.OpenRead(openFileDialog1.FileName);
using (FileStream fileStream = new FileStream(openFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.Read))//这两条语句
{
using (StreamReader streamReader = new StreamReader(fileStream))
{
string line = null;
while ((line = streamReader.ReadLine()) != null)
{
string[] str = line.Split('|');
string name = str[0];
int age = int.Parse(str[1]);
string strConn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\传智博客练习\AdoNet\文件导入导出\Person.mdf;Integrated Security=True;User Instance=True";
using (SqlConnection conn = new SqlConnection(strConn))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "insert into T_Person(Name,Age) values(@NM,@AG)";
cmd.Parameters.Add(new SqlParameter("NM", name));
cmd.Parameters.Add(new SqlParameter("AG", age));
cmd.ExecuteNonQuery();
}
}
}
MessageBox.Show("插入成功"); // 删除数据表全部内容 delete from T_Person;
}
}
}
}
private void btnExport_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
#region
string strConn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\传智博客练习\AdoNet\文件导入导出\Person.mdf;Integrated Security=True;User Instance=True";
using (SqlConnection conn = new SqlConnection(strConn))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Select * from T_Person";
using (SqlDataReader dataReader = cmd.ExecuteReader())
{
int count = 0;
while (dataReader.Read())
{
int ID = dataReader.GetInt32(dataReader.GetOrdinal("id"));
string NAME = dataReader.GetString(dataReader.GetOrdinal("Name"));
int AGE = dataReader.GetInt32(dataReader.GetOrdinal("Age"));//dataReader必须用.GetInt32,不可以parse什么的。
File.AppendAllText(Path.GetFullPath(saveFileDialog1.FileName), ID + "|"+NAME + "|"+AGE+"\r\n"); // 文件中换行"\r\n"
count++;
}
MessageBox.Show(count + "条记录被导出");
}
}
}
#endregion
}
else
{
return;
}
}
}
}