C# · 12月 25, 2021

c#数据库与TXT导入导出的实例

复制代码 代码如下:
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();
}
}
}
}
}
Message@R_16_2419@.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();
}
}
}
}
}
}
Message@R_16_2419@.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());
}