using Casic.Birmm.RbFreqStandMeasure.Tools; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Windows.Forms; namespace Casic.Birmm.RbFreqStandMeasure.tools { static class DataHelper { /// <summary> /// 执行Cmd命令 /// </summary> /// <param name="workingDirectory">要启动的进程的目录</param> /// <param name="command">要执行的命令</param> public static string StartCmd(String workingDirectory, String command) { try { using (Process p = new Process()) { string strOutput = ""; //Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = "/C" + command;// "/c"标示执行完命令后退出 p.StartInfo.WorkingDirectory = workingDirectory; p.StartInfo.UseShellExecute = false;//不启用shell 启动进程 p.StartInfo.RedirectStandardInput = true;//重定向输入 p.StartInfo.RedirectStandardOutput = true;//重定向标准输出 p.StartInfo.RedirectStandardError = true;//重定向错误输出 p.StartInfo.CreateNoWindow = true;//不创建新窗口 //如何判断CMD语句是否执行成功??? try { if (p.Start())//执行 { p.WaitForExit();//等待程序执行完,退出进程 strOutput = p.StandardOutput.ReadToEnd();//获取返回值 } } catch (Exception exp) { MessageBox.Show(exp.Message, "软件提示"); } finally { if (p != null) p.Close(); } return strOutput; } } catch (Exception ex) { MessageBox.Show(ex.Message); return ""; } } /// <summary> /// 数据库备份 /// </summary> /// <param name="ip">数据库IP</param> /// <param name="port">数据库端口</param> /// <param name="dbName">数据库名</param> /// <param name="userName">用户名</param> /// <param name="userPsw">用户密码</param> /// <param name="filepath">本分路径</param> /// <param name="characterset">数据库数据格式</param> public static void Backup(string filepath) { try { string ip = ConfigHelper.GetAppConfig("server"); string port = ConfigHelper.GetAppConfig("databasePort"); string dbName = ConfigHelper.GetAppConfig("databaseName"); string userName = ConfigHelper.GetAppConfig("databaseUser"); string userPsw = ConfigHelper.GetAppConfig("databasePassword"); string strCmd = string.Format("mysqldump -u{0} -p{1} {2}>\"{3}\"", userName, userPsw, dbName, filepath);//中间不能有空格 string strDbPath = Application.StartupPath;//mySql安装路径 try { StartCmd(strDbPath, strCmd); if (File.Exists(filepath)) { MessageBox.Show("备份成功!"); //strFilePath = sf.FileName; } } catch (Exception ex) { MessageBox.Show(ex.Message); } } catch (Exception ex) { LogHelper.WriteErrorLog(MethodBase.GetCurrentMethod().DeclaringType, "数据库备份失败!\r\n" + ex.Message); throw new Exception("数据库备份失败!\r\n" + ex.ToString()); } } /// <summary> /// 数据库还原 /// </summary> /// <param name="ip">数据库IP</param> /// <param name="port">数据库端口</param> /// <param name="dbName">数据库名</param> /// <param name="userName">用户名</param> /// <param name="userPsw">用户密码</param> /// <param name="filepath">本分路径</param> /// <param name="characterset">数据库数据格式</param> public static void Restore(string filepath) { string ip = ConfigHelper.GetAppConfig("server"); string port = ConfigHelper.GetAppConfig("databasePort"); string dbName = ConfigHelper.GetAppConfig("databaseName"); string userName = ConfigHelper.GetAppConfig("databaseUser"); string userPsw = ConfigHelper.GetAppConfig("databasePassword"); //string command = "mysql --port=端口号 --user=用户名 --password=密码 数据库名<还原文件所在路径"; //在文件路径后面加上""避免空格出现异常 string strCmd = string.Format("mysql --default-character-set=utf8 --user={0} --password={1} {2}<{3}", userName, userPsw, dbName, filepath); string strDbPath = Application.StartupPath;//mySql安装路径 try { // StartCmd(path, "create database " + Databasename.Text.ToString()+";"); string strReturn = StartCmd(strDbPath, strCmd); if (string.IsNullOrWhiteSpace(strReturn)) { MessageBox.Show("还原成功!"); } } catch (Exception ex) { MessageBox.Show("数据库还原失败!\r\n" + ex.Message.ToString()); } } public static T DataRowToModel<T>(DataRow row) { T t = default(T); PropertyInfo[] propertypes = null; string tempName = string.Empty; t = Activator.CreateInstance<T>(); propertypes = t.GetType().GetProperties(); foreach (PropertyInfo pro in propertypes) { tempName = pro.Name; if (row.Table.Columns.Contains(tempName)) { object value = row[tempName]; if (value.GetType() == typeof(System.DBNull)) { value = null; } pro.SetValue(t, value, null); } } return t; } /// <summary> /// DataTable转换为实体对象 /// </summary> public static T ConvertToEntity<T>(DataTable dt, DataRow row) where T : new() { T t = new T(); try { System.Data.DataColumnCollection columns = dt.Columns; int iColumnCount = columns.Count; int i; int j; Type elementType; elementType = t.GetType(); System.Reflection.PropertyInfo[] publicProperties = elementType.GetProperties(); //if (!(publicProperties.Length > iColumnCount)) //{ for (i = 0; i < iColumnCount; i++) { for (j = 0; j < publicProperties.Length; j++) { if (columns[i].ColumnName.ToLower().Replace("_", "") == publicProperties[j].Name.ToLower().Replace("_", "")) { if (publicProperties[j].PropertyType == typeof(int)) { int num = 0; try { num = Convert.ToInt32(row[i]); } catch { } publicProperties[j].SetValue(t, num, null); } else if (publicProperties[j].PropertyType == typeof(string) && row[i] == System.DBNull.Value) { publicProperties[j].SetValue(t, null, null); } else if (columns[i].DataType == typeof(byte[])) { object value = row[i] == System.DBNull.Value ? null : Convert.ToBase64String((byte[])row[i]); publicProperties[j].SetValue(t, value, null); } else { object value = row[i] == System.DBNull.Value ? null : row[i]; publicProperties[j].SetValue(t, value, null); } } } } } catch (Exception e) { MessageBox.Show(e.Message); } return t; } public static DataTable ConvertToDataTable<T>(this IEnumerable<T> list) { DataTable dtResult = new DataTable(); List<PropertyInfo> propertiyInfos = new List<PropertyInfo>(); //生成各列 Array.ForEach<PropertyInfo>(typeof(T).GetProperties(), p => { propertiyInfos.Add(p); dtResult.Columns.Add(p.Name, p.PropertyType); }); //生成各行 foreach (var item in list) { if (item == null) { continue; } DataRow dataRow = dtResult.NewRow(); propertiyInfos.ForEach(p => dataRow[p.Name] = p.GetValue(item, null)); dtResult.Rows.Add(dataRow); } return dtResult; } } }