我有一个连接到MYSQL的Netbeans Java项目,用于从我的数据库中读取数据。
但是MYSQL服务没有运行,我必须手动启动它。我可以在我的代码中启动此服务吗? Windows Services
此解决方案特定于Windows,并假定MySQL服务名称为MySQL80(如屏幕截图所示)。如果MySQL服务未在Windows中从Java运行,则启动MySQL服务:
getServiceState()
。
如果服务未运行(因为getServiceState()
返回“STOPPED”),请运行BAT文件的快捷方式(以管理员身份)启动服务。请参阅下面的代码中的方法startService()
,并根据需要设置String shortcut
的值。
如果服务已在运行(getServiceState()
返回“RUNNING”),或者无法识别服务名称,则代码不执行任何操作。
如果启动服务时出现问题,则会显示错误流。这是代码:
package servicestarter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ServiceStarter {
public static void main(String[] args) {
try {
ServiceStarter ss = new ServiceStarter();
String serviceName = "MySQL80";
String serviceStatus = ss.getServiceState(serviceName);
if ("STOPPED".equals(serviceStatus)) {
System.out.println("Service " + serviceName + " is stopped. Starting the service...");
String shortcut = "D:\\temp\\netstartmysql80.bat.lnk";
Process process = ss.startService(shortcut);
// Display any error output. Should be nothing there if all goes well...
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private String getServiceState(String serviceName) throws IOException {
String state = "";
Process process = Runtime.getRuntime().exec("cmd.exe /c sc query " + serviceName);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("STATE")) {
String[] tokens = line.split("\\s+");
state = tokens[tokens.length - 1];
break;
}
}
reader.close();
return state; // Returns "STOPPED" or "RUNNING", or empty string for invalid service name.
}
private Process startService(String shortcut) throws IOException {
return Runtime.getRuntime().exec("cmd.exe /c " + shortcut);
}
}
方法getServiceState()
只解析sc查询MySQL80生成的内容,以确定服务的状态(“STATE”):
C:\WINDOWS\system32>sc query MySQL80
SERVICE_NAME: MySQL80
TYPE : 10 WIN32_OWN_PROCESS
STATE : 1 STOPPED
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
笔记:
String serviceName
的值以及运行的快捷方式的名称和内容来启动任何STOPPED服务。