使用C#修改MySQL數據庫用戶的root密碼
阿新 • • 發佈:2018-08-28
.sh pri ada span tst 重定向 root密碼 使用 ODB
前言
利用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 }
使用C#修改MySQL數據庫用戶的root密碼