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

时间:2024-01-24 06:34:16 


     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());    
}


标签:数据库,TXT,导入,导出
0
投稿

猜你喜欢

  • Python+Seaborn绘制分布图的示例详解

    2021-08-14 16:51:29
  • 使用Python和百度语音识别生成视频字幕的实现

    2022-02-28 23:12:42
  • php简单日历函数

    2024-05-09 14:47:05
  • mac 安装python网络请求包requests方法

    2023-08-05 09:01:41
  • Python内置函数property()如何使用

    2022-12-07 07:04:28
  • Python算法之栈(stack)的实现

    2022-09-01 15:26:15
  • 浅谈Python flask框架

    2021-04-07 00:45:43
  • vue如何使用formData传递文件类型的数据

    2024-04-30 10:33:24
  • 让ASP搭配MYSQL

    2009-10-04 20:30:00
  • 使用Python的PIL模块来进行图片对比

    2022-04-28 19:18:36
  • Python中使用不同编码读写txt文件详解

    2023-06-29 20:35:27
  • Windows10系统下Mysql8.0.13忘记root密码的操作方法

    2024-01-17 00:22:20
  • python如何使用contextvars模块源码分析

    2021-12-03 21:55:21
  • python人工智能tensorflow优化器Optimizer算法汇总

    2023-12-06 14:44:51
  • PHP平滑关闭/重启的实现方法

    2023-10-05 08:48:29
  • UTF-8 GBK UTF8 GB2312 之间的区别和关系介绍

    2022-06-12 12:15:46
  • 一篇文章带你入门python之推导式

    2022-02-05 08:29:35
  • python基础知识之字典(Dict)

    2023-08-25 20:01:44
  • 在Sql Server中调用外部EXE执行程序引发的问题

    2024-01-16 07:40:38
  • 使用Perl创建指定编码格式(如utf-8)文件的实现代码

    2023-07-28 08:11:11
  • asp之家 网络编程 m.aspxhome.com