我有n个连接到MySQL的Netbeans Java项目,用于从数据库中读取数据。
但是MYSQL服务没有运行,我必须手动启动它。 我可以在我的代码中启动该服务吗? Windows Services
答案 0 :(得分:0)
此解决方案特定于Windows,并假定MySQL服务名称为 MySQL80 (如您的屏幕快照所示)。如果不是从Windows中的Java运行MySQL服务,则要启动它:
为该 BAT 文件创建快捷方式。在Windows文件资源管理器中,显示该快捷方式的属性,单击快捷方式标签,单击高级... 按钮,然后选中以管理员身份运行 >框:
运行下面显示的Java应用程序,该应用程序将:
getServiceState()
。 getServiceState()
返回了“已停止”),请运行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
注意: