----------------------
Windows Phone 7手机开发、
.Net培训、期待与您交流! ----------------------
下面是数据导出的代码
---------------------- Windows Phone 7手机开发、 .Net培训、期待与您交流! ----------------------详细请查看: http://net.itheima.com/
先看一段代码:
if (importDialog.ShowDialog() != DialogResult.OK)
{
return;
}
using (FileStream filestream = File.OpenRead(importDialog.FileName))
{
using (StreamReader streamreader = new StreamReader(filestream))
{
string line = null;
while ((line = streamreader.ReadLine()) != null)
{
string[] strs = line.Split('|');
string name = strs[0];
string password = strs[1];
using(SqlConnection conn=new SqlConnection(@"Data Source=.\;Database=test;user=**;password=2222;"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "insert into t_users (username,password) values (@name,@password)";
cmd.Parameters.Add(new SqlParameter("name", name));
cmd.Parameters.Add(new SqlParameter("password", password));
cmd.ExecuteNonQuery();
}
}
}
}
}
MessageBox.Show("导入成功!");
这样写虽然可以实现数据导入的功能,但是执行效率很慢。因为每处理一行数据都会创建一次连接,数据库在初次连接时是很慢的;
因此,应该在所有数据都导入完毕后才关闭数据库连接,并且SQLCOMMAND也应该重用,但这里要注意SQLcommand不能重复的添加参数,因此在每次循环时,都要清除一下参数,否则会报错。
if (importDialog.ShowDialog() != DialogResult.OK)
{
return;
}
using (FileStream filestream = File.OpenRead(importDialog.FileName))
{
using (StreamReader streamReader = new StreamReader(filestream))
{
using (SqlConnection conn = new SqlConnection(@"Data Source=./;Database=test;User=**;Password=******"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "insert into t_users(username,password) values (@name,@password)";
string line = null;
while ((line = streamReader.ReadLine()) != null)
{
string[] strs = line.Split('|');
string name = strs[0];
string password = strs[1];
cmd.Parameters.Clear();//参数不能重复添加,在while循环中用的就只有一个sqlcommand,因此每次添加的时候要使用clear方法清除原来的参数;
cmd.Parameters.Add("name", name);
cmd.Parameters.Add("password", password);
cmd.ExecuteNonQuery();
}
}
}
}
}
MessageBox.Show("导入成功");
下面是数据导出的代码
if (outputFileDialog.ShowDialog() != DialogResult.OK)
{
return;
}
using (SqlConnection conn = new SqlConnection(@"Data Source=.\;Database=test;User=***;password=*****"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select username,password from t_users";
SqlDataReader reader=cmd.ExecuteReader();
string line = null;
string filePath = outputFileDialog.FileName;
while (reader.Read()) //逐条读取数据库表的记录,当读取完最后一行时,显示false
{
line= reader.GetString(0) + '|' + reader.GetString(1);//getstring方法得到指定列的数据
using (StreamWriter streamWriter = new StreamWriter(filePath,true,Encoding.Default))
//第二个参数设为true表示在指定文件的末尾增加,而不删除原有的文件
{
streamWriter.WriteLine(line);
streamWriter.Flush();
}
}
}
}
MessageBox.Show("导出成功!");
---------------------- Windows Phone 7手机开发、 .Net培训、期待与您交流! ----------------------详细请查看: http://net.itheima.com/