using System.Data.SqlClient;
using System.IO;
using System.Configuration;
namespace 表转txt txt转表
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static string path = ConfigurationManager.AppSettings["path"].ToString().Trim();
private static string daochu = ConfigurationManager.AppSettings["daochu"].ToString().Trim();
private static string daoru = ConfigurationManager.AppSettings["daoru"].ToString().Trim();
private void Form1_Load(object sender, EventArgs e)
{
#region 将数据库中的表导出成.txt格式的文件
string txt = "";
SqlConnection sqlcon = new SqlConnection(daochu);
sqlcon.Open();
string tt = "select * from Permissions";
SqlDataAdapter sda = new SqlDataAdapter(tt, sqlcon);
DataTable dt = new DataTable();
try
{
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j == (dt.Columns.Count - 1))
{
txt += "" + dt.Rows[i][j].ToString().Trim() + "";
}
else
{
txt += "" + dt.Rows[i][j].ToString().Trim() + "|";
}
}
Login(txt);
txt = "";
}
}
MessageBox.Show("成功导出文件");
}
catch (Exception ex)
{
MessageBox.Show("未能成功导出文件");
}
sqlcon.Close();
dt.Dispose();
#endregion
Reader();
}
public void Reader()
{
#region 将.txt格式文件导入成数据库中的表
SqlConnection conn = new SqlConnection(daoru);
conn.Open();
string se = "if not exists(select * from sysobjects where id=object_Id('HumanInformation.Permissions') )CREATE TABLE Permissions(PermissionsId VarChar(15),PermissionsName VarChar(15)) ";
SqlCommand sa = new SqlCommand(se, conn);
try
{
sa.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
Console.WriteLine(ex.Message);
}
conn.Close();
Set();
#endregion
}
public void Login(string txt)
{
string path = @"" + Form1.path + "";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fp = path + "Permissions.txt";
StringBuilder str = new StringBuilder();
str.Append("" + txt + "");
StreamWriter sw;
if (!File.Exists(fp))
{
sw = File.CreateText(fp);
}
else
{
sw = File.AppendText(fp);
}
sw.WriteLine(str.ToString());
sw.Close();
}
public void Set()
{
StreamReader sr = new StreamReader(new FileStream("" + path + "Permissions.txt", FileMode.Open, FileAccess.Read), System.Text.Encoding.Default);
SqlConnection cn = new SqlConnection(daoru);
string insertCmd = "insert into Permissions values (@id, @name)";
char[] delimChar = new char[] { '|' };
string[] split = null;
string strTemp = sr.ReadLine();
while (strTemp != null)
{
split = strTemp.Split(delimChar);
SqlCommand cmd = new SqlCommand(insertCmd, cn);
cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = split[0];
cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = split[1];
cn.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
Console.WriteLine(ex.Message);
}
cn.Close();
strTemp = sr.ReadLine();
}
MessageBox.Show("成功导入数据库");
sr.Close();
}
}
}
将表导出数据库成.txt文件 将.txt文件导入数据库成表
最新推荐文章于 2024-08-22 09:42:15 发布