自制mysql服务器的关键程序,把这段程序放到线程中运行就可以开启mysql服务了。需要的同学可以参考下。
private void runMysql()
{
Process p=new Process();
string constr="server=localhhost;port=3306;database=dbname;user=root;password='123456';";
MySqlConnection con=new MySqlConnection(constr);
p.StartInfo.FileName="cmd.exe";
p.StartInfo.UseShellExecute=false;
p.StartInfo.RedirectStandardInput=true;
p.StartInfo.RedirectStandardOutput=true;
p.StartInfo.RedirectStandardError=true;
p.StartInfo.CreateNoWindow=true;
p.Start();
//mysql执行文件的位置
string spath="c:\\users\\...\\mysql\\bin\\mysqld.exe";
System.IO.StreamWriter sw=p.StandardInput;
sw.WriteLine(spath);
sw.Flush();
p.StandardInput.WriteLine("exit");
//线程中显示信息需要用到委托,具体参考FillComboBoxCallback
ShowMessage("Mysql在初始化...");
while(Process.GetProcessNyName("mysqld").Length==0)
{
string strres=string.Empty;
var output = new List<string>();
while(p.StandardOutput.Peek()>-1)
{
strres+=p.StandardOutput.ReadLine();
}
if(Process.GetProcessNyName("mysqld").Length==0)
{
Thread.Sleep(5);
}
}
p.Close();
System.Data.DataTable dt=new System.Data.DataTable();
while(dt.Rows.Count==0)
{
string sqlstr="select table_name from information_schema.tables where table_schema='数据库名'";
try{
while(con.State.ToString()!="Open")
{
con.Open();
}
MySqlDataAdapter mda=new MySqlDataAdapter(sqlstr,con);
System.Data.DataSet ds=new System.Data.DataSet();
mda.Fill(ds);
dt=ds.Tables[0];
FillComboBox(comboBOx1,dt);
if(dt.Rows.Count==0)
{
Thread.Sleep(5);
}
}
catch(Exception ex)
{
}
}
}
delegate void FillComboBoxCallback(ComboBox cb,System.Data.DataTable dt);
void FillComboBox(ComboBox cb,System.Data.DataTable dt)
{
if(this.InvokeRequired)
{
this.Invoke(new FillComboBoxCallback(FillComboBox),new object[]{cb,dt});
}else
{
for(int m=0;m<dt.Rows.Count;m++)
{
cb.Items.Add(dt.Rows[m][0].ToString());
}
cb.Text=cb.Items[0].ToString();
}
}
启动后,就可以用con来获取数据库的内容了,当然也可以修改编辑。