当前位置: 编程技术>.net/c#/asp.net
c#数据库与TXT导入导出的实例
来源: 互联网 发布时间:2014-10-19
本文导语: 代码如下: private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { using (FileStream fs = File.OpenRead(openFileDialog1.FileName)) ...
代码如下:
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
using (FileStream fs = File.OpenRead(openFileDialog1.FileName))
{
using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding("GB2312")))
{
//必需设置字符编码System.Text.Encoding.GetEncoding("GB2312"),
不然string name = arr[0]中的name就是乱码 using (SqlConnection conn = new SqlConnection(@"Data Source=.SQLEXPRESS;AttachDbFilename='|DataDirectory|dd.mdf';
Integrated Security=True;User Instance=True"))
{
//DataDirectory指的是数据库的绝对路径,winForm里面的Program.cs必需添加代码,否则是.NET是找到的数据库是有问题的,实在不懂可以去博客园自己去看看why
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "insert into T_Persons values(@Name,@Age)";
string line = "";
while ((line = sr.ReadLine()) != null)
{
string[] arr = line.Split('|');
string name = arr[0];
int age = Convert.ToInt32(arr[1]);
cmd.Parameters.Clear();//别忘了
cmd.Parameters.Add(new SqlParameter("Name", name));
cmd.Parameters.Add(new SqlParameter("Age", age));
cmd.ExecuteNonQuery();
}
}
}
}
}
MessageBox.Show("txt导入数据库成功!");
}
}
private void button2_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (FileStream fs = File.OpenWrite(saveFileDialog1.FileName))
{
using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("GB2312")))
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.SQLEXPRESS;AttachDbFilename='|DataDirectory|dd.mdf';Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from T_Persons";
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
string name = sdr.GetString(sdr.GetOrdinal("Name"));
int age = sdr.GetInt32(sdr.GetOrdinal("Age"));
string line =name+"|"+age;
sw.WriteLine(line);
sw.Flush();
}
}
}
}
}
}
MessageBox.Show("导出数据到txt成功!");
}
}
这是要在Program.cs文件中添加的代码,它只对winForm和win控制台有效:
代码如下:
static void Main()
{
string dataDir = AppDomain.CurrentDomain.BaseDirectory;
if (dataDir.EndsWith(@"binDebug") || dataDir.EndsWith(@"binRelease"))
{
dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}