这篇主要将winform程序中如何安装mysql数据库及服务,ε=(´ο`*)))唉,不太好表达,类直接拿去用吧,还有纯净版的mysql数据库(不知道怎么在页面中上传,就上传到我的资源里了1积分下载,有需要的朋友我也可以直接发你),只不过在程序运行前需要检测数据库服务是否启用,类中也有,调用加判断下即可。
using DAL;
using IBatisNet.Common.Logging;
using log4net;
using NetFwTypeLib;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
namespace SCDParseTool
{
///
/// 数据库管理类
/// 包含数据库的安装、数据库的卸载、更新sqlMap.config文件的数据库连接字符串
///
public static class DataManagement
{
///
/// log4net日志组件
///
private static log4net.ILog Log = log4net.LogManager.GetLogger(typeof(DataManagement));
public static string ip = "localhost";
public static string uid = "root";
public static string pwd = "123456";
public static string port = "53307";//端口
///
/// 设置防火墙属性
///
private static INetFwMgr netFwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr"));
///
/// 安装数据库服务
///
public static string InstallDataBase()
{
#region 安装数据库服务
string result = string.Empty;
try
{
//MySQL数据库ini文件路径
string dbPath = AppDomain.CurrentDomain.BaseDirectory + "database\\";
//判断当前数据库路径中是否存在空格
bool isValidPath = dbPath.Contains(" ");
string currentSettingFile = dbPath + "my_mysql.ini";
string defaultSettingFile = AppDomain.CurrentDomain.BaseDirectory + "database\\" + "mysql.ini";
string targetFile = Environment.SystemDirectory.Substring(0, Environment.SystemDirectory.Length - 9) + "\\my_scimmanagement.ini";
//如果存在当前配置文件,则删除
if (File.Exists(currentSettingFile))
{
FileInfo info = new FileInfo(currentSettingFile);
if (info.Attributes.ToString().IndexOf("ReadOnly") != -1)
{
info.Attributes = FileAttributes.Normal;
}
File.Delete(currentSettingFile);
}
FileStream stream = new FileStream(currentSettingFile, FileMode.Create);
StreamWriter writer = new StreamWriter(stream, Encoding.Default);
string baseDir = dbPath.Replace("\\", "\\\\");
writer.Write("[WinMySQLAdmin]\r\n");
writer.Write("Server=" + baseDir + "bin\\\\mysqld.exe\r\n");
writer.Write("\r\n");
writer.Write("[client]\r\n");
writer.Write("port=53307\r\n");
writer.Write("default-character-set=utf8\r\n");
writer.Write("\r\n");
writer.Write("[mysql]\r\n");
writer.Write("default-character-set=utf8\r\n");
writer.Write("\r\n");
writer.Write("[mysqld]\r\n");
writer.Write("port=53307\r\n");
writer.Write("basedir=" + baseDir + "\r\n");
writer.Write("datadir=" + baseDir + "data\\\\\r\n");
writer.Write("log-error=" + baseDir + "log-error.txt\r\n");
writer.Write(File.ReadAllText(defaultSettingFile));
writer.Flush();
writer.Close();
stream.Close();
//如果当前安装路径中存在空格,则将MySQL配置存放在系统分区Windows分区下
if (isValidPath)
{
if (File.Exists(targetFile))
{
FileInfo info2 = new FileInfo(targetFile);
if (info2.Attributes.ToString().IndexOf("ReadOnly") != -1)
{
info2.Attributes = FileAttributes.Normal;
}
File.Delete(targetFile);
}
File.Copy(currentSettingFile, targetFile);
currentSettingFile = targetFile;
}
Process process = new Process
{
StartInfo = { FileName = "cmd.exe", UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, CreateNoWindow = true }
};
//将MySQL配置成Windows服务器
process.Start();
process.StandardInput.WriteLine("cd " + dbPath + "bin");
process.StandardInput.WriteLine("mysqld --install MysqlServer --defaults-file=" + currentSettingFile);
process.StandardInput.WriteLine("net start MysqlServer");
process.StandardInput.WriteLine("exit");
int timeout = 60000;//程序执行时间
process.WaitForExit(timeout); ;
result = process.StandardOutput.ReadToEnd();
process.Close();
}
catch (UnauthorizedAccessException uae)
{
MessageBox.Show("数据库服务安装失败\n请以管理员身份来运行此程序!", "数据库管理");
Log.Error("安装数据库服务错误信息:" + uae.Message);
}
catch (Exception exception)
{
MessageBox.Show("数据库服务安装失败\n" + exception.ToString(), "数据库管理");
Log.Error("安装数据库服务错误信息:" + exception.Message);
}
try
{
netFwMgr.LocalPolicy.CurrentProfile.FirewallEnabled = true;
netFwMgr.LocalPolicy.CurrentProfile.ExceptionsNotAllowed = false;
netFwMgr.LocalPolicy.CurrentProfile.NotificationsDisabled = true;
}
catch (Exception ee)
{
Log.Error(ee.Message);
}
return result;
#endregion 安装数据库服务
}
///
/// 查看数据库服务是否存在
///
///
public static bool CheckDataBaseService()
{
bool state = false;
ServiceController[] service = ServiceController.GetServices();
string serviceName = "MysqlServer";
for (int i = 0; i < service.Length; i++)
{
if (string.Equals(service[i].ServiceName, serviceName,StringComparison.InvariantCultureIgnoreCase))
{
state = true;
break;
}
}
return state;
}
///
/// 卸载数据库服务
///
///
public static string uninstallDataBase()
{
#region 卸载数据库服务
string result = string.Empty;
try
{
string dbPath = AppDomain.CurrentDomain.BaseDirectory + "database\\";
string iniPath = dbPath + "my_mysql.ini";
Process process = new Process
{
StartInfo = { FileName = "cmd.exe", UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, CreateNoWindow = true }
};
process.Start();
process.StandardInput.WriteLine("net stop MysqlServer");
process.StandardInput.WriteLine("sc delete MysqlServer");
process.StandardInput.WriteLine("exit");
process.WaitForExit(0xea60);
result = process.StandardOutput.ReadToEnd();
process.Close();
dbPath = dbPath + @"bin\mysqld.exe";
netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Remove(dbPath);
if (result.Contains("成功"))
{
MessageBox.Show("数据库服务卸载成功", "数据库管理");
}
else
{
MessageBox.Show("数据库服务卸载失败", "数据库管理");
}
}
catch (Exception exception)
{
MessageBox.Show("数据库服务卸载失败\n" + exception.ToString(), "数据库管理");
Log.Error("卸载数据库服务错误信息:" + exception.Message);
}
return result;
#endregion 卸载数据库服务
}
///
/// 更新SqlMap.config文件中的数据库连接字符串
///
///
///
///
///
public static void DatabaseConnection(string Ip, string uid, string pwd, string port)
{
string sqlMapFile = AppDomain.CurrentDomain.BaseDirectory + "SqlMap.config";
string connectionString = string.Empty;
if (File.Exists(sqlMapFile))
{
XmlDocument document = new XmlDocument();
document.Load(sqlMapFile);
XDocument xDocument = XDocument.Load(sqlMapFile);
//因为SqlMap.config带有命名空间,因此必须添加命名空间
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(document.NameTable);
namespaceManager.AddNamespace("a", "http://ibatis.apache.org/dataMapper");
namespaceManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
//使用XPath时必须使用添加了的命名空间
XmlElement node = (XmlElement)document.SelectSingleNode("//a:sqlMapConfig/a:database/a:dataSource[@name='MySqlSource']", namespaceManager);
if (node != null)
{
connectionString = string.Format("Server={0};Database=scim_base;Uid={1};Pwd={2};Port={3};Connection Timeout = 180; Allow Zero Datetime = True", Ip, uid, pwd, port);
node.SetAttribute("connectionString", connectionString);
document.Save(sqlMapFile);
SqlMapperManager.Instance.DataSource.ConnectionString = connectionString;
// MessageBox.Show("保存成功!");
}
else
{
MessageBox.Show("保存失败,请确认SqlMap.config中是否存在dataSource节点!");
}
}
else
{
MessageBox.Show("保存失败,请确认是否存在SqlMap.config文件!");
}
}
}
}