我想在Java中创建一个访问存储在外部服务器中的数据库的Web服务。我创建了一个包含主要信息的BeepWebService类:
@WebService
public class BeepWebService {
private Connection conn = null;
private String url = "jdbc:mysql://xxxxxx.ipagemysql.com/";
private String dbName = "beep";
private String userName = "beep_user_name";
private String password = "pswrd";
private String db_str = " select Name beep.SW where Name = ";
public BeepWebService(){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
this.conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
}catch (Exception e) {
System.out.print("failed");
}
}
@WebMethod
public String returnFormat(@WebParam(name="input_value") String input){
String str = null;
String query = db_str+input;
try {
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
str = rs.getString(2);
System.out.println(str);
}
rs.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return str;
}
}
然后我创建了名为BeepWebServicePublisher的发布者类:
public class BeepWebServicePublisher {
public static void main(String[] args){
System.out.println("Web Service initiating...");
Endpoint.publish("http://xxxxxx.ipagemysql.com/", new BeepWebService());
}
}
不幸的是,在成功编译两个类并运行应用程序之后,输出消息“失败”(意味着无法与数据库建立连接),然后是异常错误。这是完整的输出:
Web Service starting..
failedException in thread "main" com.sun.xml.internal.ws.server.ServerRtException: Server Runtime Error: java.net.BindException: Address already in use: bind
at com.sun.xml.internal.ws.transport.http.server.ServerMgr.createContext(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.HttpEndpoint.publish(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.publish(Unknown Source)
at com.sun.xml.internal.ws.spi.ProviderImpl.createAndPublishEndpoint(Unknown Source)
at javax.xml.ws.Endpoint.publish(Unknown Source)
at com.BeepServicePackage.server.BeepWebServicePublisher.main(BeepWebServicePublisher.java:17)
Caused by: java.net.BindException: Address already in use: bind
at sun.nio.ch.Net.bind(Native Method)
at sun.nio.ch.ServerSocketChannelImpl.bind(Unknown Source)
at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source)
at sun.net.httpserver.ServerImpl.<init>(Unknown Source)
at sun.net.httpserver.HttpServerImpl.<init>(Unknown Source)
at sun.net.httpserver.DefaultHttpServerProvider.createHttpServer(Unknown Source)
at com.sun.net.httpserver.HttpServer.create(Unknown Source)
... 6 more
由于我是这个领域的新手,有人可以告诉我代码中是否有问题或服务器可能出现问题?谢谢!
答案 0 :(得分:2)
打印出整个堆栈跟踪;它会为您提供比“失败”消息更多的信息。
您在哪里注册MySQL JDBC驱动程序?我没有看到它。
更新:我建议您解决问题。不要将数据库代码放在Web服务中。创建一个基于接口的POJO,您可以离线测试。让它工作,然后将实例提供给Web服务使用。
你有99个问题,儿子。首先修复一个。
这是错误的:
private String db_str = " select Name beep.SW where Name = ";
您需要一个绑定参数:
private String db_str = " select Name beep.SW where Name = ?";
您需要PreparedStatement
,而不是Statement
。
然后你想绑定你传入的名字。
SELECT
只返回一列;为什么你在第2栏上setString
?
在很多方面都错了。