标签:bcd apt cdata drive 创建 连接数据库 设定 comm option
前言
利用C#调用CMD窗口实现修改数据库密码
实现思路:
先通过odbc连接数据库,获取到Mysql的根目录。根据根目录的路径调用CMD,连接MySQL,实现修改MySQL数据库密码。
1 private void modifyPath_Click(object sender, EventArgs e) 2 { 3 bool isD = true; 4 string MysqlPath = string.Empty; 5 try 6 { 7 //获取MySQL安装路径 8 DataTable db = ExecuteQuery("select @@basedir as basePath from dual","123"); 9 string sqlPath = string.Empty; 10 sqlPath = db.Rows[0]["basePath"].ToString(); 11 //只判断目录在C/D盘的可能 12 if (sqlPath.Contains("D:")) 13 { 14 path = sqlPath.Replace("D:", ""); 15 } 16 else 17 { 18 path = sqlPath.Replace("C:", ""); 19 isD = false; 20 } 21 } 22 catch 23 { 24 Application.Exit(); 25 } 26 27 Process process = new Process();//创建进程对象 28 try 29 { 30 ProcessStartInfo startInfo = new ProcessStartInfo(); 31 startInfo.FileName = "cmd.exe";//设定需要执行的命令 32 //startInfo.Arguments = "/C " + 2;//“/C”表示执行完命令后马上退出 33 startInfo.UseShellExecute = false;//不使用系统外壳程序启动 34 startInfo.RedirectStandardInput = true;//不重定向输入 35 startInfo.RedirectStandardOutput = true; //重定向输出 36 //startInfo.RedirectStandardError = true; //重定向标准错误输出 37 startInfo.CreateNoWindow = true;//不创建窗口 38 process.StartInfo = startInfo; 39 if (process.Start())//开始进程 40 { 41 string newPsd = "123456"; 42 newPsd = "mysqladmin -u root -p123 password " + newPsd; 43 if (isD) 44 { 45 process.StandardInput.WriteLine("d:"); 46 } 47 else 48 { 49 process.StandardInput.WriteLine("cd\\"); 50 } 51 process.StandardInput.WriteLine("cd" + path +"bin"); 52 process.StandardInput.WriteLine(newPsd); 53 } 54 } 55 catch (Exception ex) 56 { 57 ex.ToString(); 58 } 59 finally 60 { 61 if (process != null) 62 process.Close(); 63 } 64 }
//备注: 密码可以采用密文的方式,此处为了方便
连接数据库语句ExecuteQuery的方法
1 public static DataTable ExecuteQuery(string commandText, string psd) 2 { 3 DataSet dataSet = new DataSet(); 4 string connectionString = "DRIVER={MySQL ODBC 3.51 Driver};SERVER=localhost;OPTION=3;UID=root;PASSWORD=" + psd + ";Stmt=SET NAMES gb2312;"; 5 IDbConnection dbConnection = new OdbcConnection(connectionString); 6 DataTable result; 7 try 8 { 9 if (dbConnection.State == ConnectionState.Closed) 10 { 11 dbConnection.Open(); 12 } 13 IDbCommand dbCommand = dbConnection.CreateCommand(); 14 dbCommand.CommandText = commandText; 15 ((IDataAdapter)new OdbcDataAdapter 16 { 17 SelectCommand = dbCommand 18 }).Fill(dataSet); 19 result = dataSet.Tables[0]; 20 } 21 catch (Exception ex) 22 { 23 MessageBox.Show("系统不兼容,配置失败"); 24 Application.Exit(); 25 result = null; 26 } 27 finally 28 { 29 try 30 { 31 dbConnection.Close(); 32 } 33 catch 34 { 35 } 36 } 37 return result; 38 }
标签:bcd apt cdata drive 创建 连接数据库 设定 comm option
原文地址:https://www.cnblogs.com/MacrossFT/p/9532285.html