c#数据库与TXT导入导出的实例
程序员文章站
2023-12-14 15:28:10
复制代码 代码如下: private void button1_click(object sender, eventargs...
复制代码 代码如下:
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")))
{
//<span style="color:#3333ff;">必需设置字符编码system.text.encoding.getencoding("gb2312"),
不然string name = arr[0]中的name就是乱码</span> using (sqlconnection conn = new sqlconnection(@"data source=.\sqlexpress;attachdbfilename='|datadirectory|\dd.mdf';
integrated security=true;user instance=true"))
{
//<span style="color:#3333ff;">datadirectory指的是数据库的绝对路径,winform里面的program.cs必需添加代码,否则是.net是找到的数据库是有问题的,实在不懂可以去博客园自己去看看why</span>
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成功!");
}
}
</span>
这是要在program.cs文件中添加的代码,它只对winform和win控制台有效:
复制代码 代码如下:
static void main()
{
string datadir = 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());
}