本帖最后由 Always. 于 2013-9-22 22:58 编辑
我实现了将数据从一个txt文件中导入到VS2010中创建的数据库中。
代码如下:- if(ofdImport.ShowDialog()!=DialogResult.OK)
- {
- MessageBox.Show("导入失败");
- }
- 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);
- }
- using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\我的第一个mdf解决\数据导入导出\Database4.mdf;Integrated Security=True;User Instance=True"))
- {
- conn.Open();
- using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\我的第一个mdf解决\数据导入导出\Database4.mdf;Integrated Security=True;User Instance=True"))
- {
- conn.Open();
- using (SqlCommand cmd = conn.CreateCommand())
- {
- cmd.CommandText = "insert into T_Persons values(@name,@age)";
- using (FileStream filestream = File.OpenRead(ofdImport.FileName)) //打开这个文件
- {
- using (StreamReader streamreader = new StreamReader(filestream)) //读取导入的这个文件
- {
- string line = null;
- while ((line = streamreader.ReadLine()) != null)
- {
- string[] remove = line.Split('|');
- string name = remove[0];
- int age = Convert.ToInt32(remove[1]);
- cmd.Parameters.Clear();
- cmd.Parameters.Add(new SqlParameter("name", name));
- cmd.Parameters.Add(new SqlParameter("@age", age));
- cmd.ExecuteNonQuery();
- }
- }
- }
- }
- }
复制代码 VS2010中创建的数据库 中导出数据到txt中
代码如下:- if (ofdOutput.ShowDialog() != DialogResult.OK)
- {
- MessageBox.Show("导出失败");
- }
- 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);
- }
- using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\我的第一个mdf解决\数据导出\Database6.mdf;Integrated Security=True;User Instance=True"))
- {
- conn.Open();
- using (SqlCommand cmd = conn.CreateCommand())
- {
- cmd.CommandText = "select * from T_Persons";
- using (SqlDataReader reader = cmd.ExecuteReader())
- {
- using (FileStream filestream = new FileStream(ofdOutput.FileName, FileMode.Append, FileAccess.Write))
- {
- StreamWriter sw = new StreamWriter(filestream);
- whlile (reader.Read()) //逐行读取每一个信息,比如第一行
- {
- string name = reader.GetString(reader.GetOrdinal("Name")); //比如读取第一行中Name那里列中的内容
- string age = reader.GetString(reader.GetOrdinal("Age")); /比如读取第一行中Age那里列中的内容
- string line = name + "|" + age;
- sw.WriteLine(line);
- }
- sw.Flush();
- }
- }
- MessageBox.Show("导出成功");
- }
-
-
复制代码 |