Java JDBC MySQL exception: “Operation not allowed after ResultSet closed” - java

So I have looked several times trough the function and nothing seems wrong. I don't pass any ResultSets to the function so I really do not get what is wrong with it. But I still get an error. The code works fine, its just that the function is used quite a lot of times and errors do not look nice on the console.
void addItemToBody(String userId, MessageReceivedEvent event, int id) throws HTTP429Exception, DiscordException, MissingPermissionsException{
String sql = "SELECT ItemType FROM items WHERE ID=?";
PreparedStatement state;
try {
state = Main.conn.prepareStatement(sql);
state.setInt(1, id);
ResultSet result = state.executeQuery();
while(result.next()){
String type = result.getString("ItemType");
if(type.equals("Head")){
state.executeUpdate("UPDATE body SET headID="+id+" WHERE playerID='"+userId+"'");
}
if(type.equals("Chest")){
state.executeUpdate("UPDATE body SET chestID="+id+" WHERE playerID='"+userId+"'");
}
if(type.equals("Pants")){
state.executeUpdate("UPDATE body SET pantsID="+id+" WHERE playerID='"+userId+"'");
}
if(type.equals("Boots")){
state.executeUpdate("UPDATE body SET bootsID="+id+" WHERE playerID='"+userId+"'");
}
if(type.equals("Melee")||type.equals("Magic")||type.equals("Ranged")){
state.executeUpdate("UPDATE body SET weaponID="+id+" WHERE playerID='"+userId+"'");
}
sendMessage("Item equipped!",event);
result.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
This is the error:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:743)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6320)
at martacus.mart.bot.rpg.InventoryHandler.addItemToBody(InventoryHandler.java:143)
at martacus.mart.bot.rpg.InventoryHandler.equipItem(InventoryHandler.java:92)
at martacus.mart.bot.rpg.InventoryHandler.OnMesageEvent(InventoryHandler.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sx.blah.discord.handle.EventDispatcher.dispatch(EventDispatcher.java:104)
at sx.blah.discord.api.internal.DiscordWS.messageCreate(DiscordWS.java:323)
at sx.blah.discord.api.internal.DiscordWS.onMessage(DiscordWS.java:144)
at org.java_websocket.client.WebSocketClient.onWebsocketMessage(WebSocketClient.java:312)
at org.java_websocket.WebSocketImpl.decodeFrames(WebSocketImpl.java:368)
at org.java_websocket.WebSocketImpl.decode(WebSocketImpl.java:157)
at org.java_websocket.client.WebSocketClient.interruptableRun(WebSocketClient.java:230)
at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:188)
at java.lang.Thread.run(Unknown Source)

You shouldn't close the ResultSet while you are still looping through it
while(result.next()){
...
result.close();
}

Related

NullPointerException when I try to access to my API on Eclipse but it's working on IntelliJ

I have a problem with my API. For one of my school project, I needed to send my project in a Eclipse workspace. But i coded it on IntelliJ because I prefer it. When I want to pass my code on Eclipse, the project doens't work so I maked a new project and put my code inside. But at the moment, I cannot acces on this API because I have a nullPointerException. The nullPointerException is on my DAO and on IntelliJ it's working.
so the error is:
Servlet.service() for servlet access.RestApplication threw exception
java.lang.NullPointerException
at model.dao.DaoComment.getAll(DaoComment.java:150)
at access.CommentAPI.getAll(CommentAPI.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
The DAO is like that:
#Override
public List<User> getAll() {
CallableStatement stmt = null;
List<User> users = new ArrayList<>();
ResultSet resultSet = null;
try {
stmt = connect.prepareCall("{? = call USERPACKAGE.getAll}");
stmt.registerOutParameter(1, OracleTypes.CURSOR);
stmt.execute();
resultSet = (ResultSet) stmt.getObject(1);
if (resultSet != null) {
while (resultSet.next()) {
User u = new User();
u.setId(resultSet.getInt(1));
u.setEmail(resultSet.getString(2));
u.setPassword(resultSet.getString(3));
u.setFirstname(resultSet.getString(4));
u.setLastname(resultSet.getString(5));
u.setAddress(resultSet.getString(6));
u.setBirthday(resultSet.getTimestamp(7));
u.setRegisterDate(resultSet.getTimestamp(8));
u.setRelationship(resultSet.getInt(9) == 1);
u.setPhoneNumber(resultSet.getInt(10));
u.setGender(resultSet.getInt(11) == 1);
u.setInterestedIn(resultSet.getInt(12) == 1);
users.add(u);
}
}
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return users;
Normally after it I take the data and send it by json but here it's not working.
the exception stack trace is:
java.util.MissingResourceException: Can't find bundle for base name sun.util.logging.resources.logging, locale en_US
at java.base/java.util.ResourceBundle.throwMissingResourceException(Unknown Source)
at java.base/java.util.ResourceBundle.getBundleImpl(Unknown Source)
at java.base/java.util.ResourceBundle.getBundleImpl(Unknown Source)
at java.base/java.util.ResourceBundle.getBundleImpl(Unknown Source)
at java.base/java.util.ResourceBundle.getBundle(Unknown Source)
at org.eclipse.glassfish.tools.log.LevelResolver.getLocalized(LevelResolver.java:49)
at org.eclipse.glassfish.tools.log.LevelResolver.<init>(LevelResolver.java:31)
at org.eclipse.glassfish.tools.log.AbstractLogFilter.<init>(AbstractLogFilter.java:36)
at org.eclipse.glassfish.tools.log.PatternLogFilterV4.<init>(PatternLogFilterV4.java:32)
at org.eclipse.glassfish.tools.log.AbstractLogFilter.createFilter(AbstractLogFilter.java:75)
at org.eclipse.glassfish.tools.log.GlassfishConsoleManager.getStandardConsole(GlassfishConsoleManager.java:53)
at org.eclipse.glassfish.tools.GlassfishServerLaunchDelegate$2.run(GlassfishServerLaunchDelegate.java:390)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:37)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:182)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:3906)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3537)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$5.run(PartRenderingEngine.java:1170)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1059)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:153)
at org.eclipse.ui.internal.Workbench.lambda$3(Workbench.java:667)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:597)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:152)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:656)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:592)
at org.eclipse.equinox.launcher.Main.run(Main.java:1498)
at org.eclipse.equinox.launcher.Main.main(Main.java:1471)
MissingResourceException points out that you are missing a resourcebundle.
Just add a file sun/util/logging/resources/logging_en_US.properties to your project.The content should look like this:
# Localizations for Level names. For the US locale
# these are the same as the non-localized level name.
# The following ALL CAPS words should be translated.
ALL=All
# The following ALL CAPS words should be translated.
SEVERE=Severe
# The following ALL CAPS words should be translated.
WARNING=Warning
# The following ALL CAPS words should be translated.
INFO=Info
# The following ALL CAPS words should be translated.
CONFIG= Config
# The following ALL CAPS words should be translated.
FINE=Fine
# The following ALL CAPS words should be translated.
FINER=Finer
# The following ALL CAPS words should be translated.
FINEST=Finest
# The following ALL CAPS words should be translated.
OFF=Off
See also this stackoverflow answer

Database Table 'PACIENTE' does not exist

I'm trying to make a java desktop database application, using the derby embedded database, I'm having some issues that I can't quite fix, and I've searched (a lot) for the answers, found some, but they couldn't solve my problem, so I decided to make a question myself. I made the database on netbeans, jut like a whole bunch of tutorials teach, downloaded the derby.jar and added to the library on the project, but then when I try to insert some data in the database's table that I created is says that the table doesn't exist.
I'm pretty sure i'm missing something really stupid, but I can't figure it out by myself, so any help will be very much appreciate. I'm new to all this java database development, I had only created local databases on c#
PS: The schema is the 'APP' one, I tried using "INSERT INTO APP.PACIENTE (ID, NOME) VALUES (1, 'victor')" but that didn't work either
public class BancoDados {
private static String url = "jdbc:derby:MeuBancoDados;create=true";
private static String driver = "org.apache.derby.jdbc.EmbeddedDriver";
static Connection conn;
static Statement sta;
public static void insert() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
conn = null;
sta = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url);
sta = conn.createStatement();
sta.executeUpdate("INSERT INTO PACIENTE (ID, NOME) VALUES (1, 'victor')");
sta.close();
conn.close();
System.out.println("Inserido com sucesso!");
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
}
}
I get This error:
Exception in thread "main" ERROR 42X05: Table 'PACIENTE' does not exist.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.sql.compile.DMLModStatementNode.verifyTargetTable(Unknown Source)
at org.apache.derby.impl.sql.compile.InsertNode.bind(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.executeUpdate(Unknown Source)
at projcad.BancoDados.insert(BancoDados.java:31)
at projcad.projcad.main(projcad.java:8)
Java Result: 1
Table 'PACIENTE' does not exist.
This is because in database you have not created the PACIENTE table.
Create it.

GWT/Mysql/Java connection to database

I'm fairly new to gwt, and figuring out the connections with a mysql database has me stumped. Since there are very few direct tutorials, I've been going off another stackoverflow question here.
http://stackoverflow.com/questions/8335322/java-gwt-mysql-connection-refused/8388422#8388422
Although I can't get it right. Few things, this project isn't using the GAE, just the GWT, as was suggested as a previous answer in the other question. Yes, I can connect to my database through another sample program, so the link to the database is open. I also imported my mysql driver to /WEB-INF/lib, as well as added it to my java build path.
The crux of this is, I don't know why I can't connect, and my console is useless, if anyone can see right off the bat what I'm doing wrong that would be fantastic, or if there was a way to print out more of the error message that would be great as well as I don't know how to view the console for the server side resources (I read somewhere that there might be more to the errors then what is shown? ) thanks.
here is my GreetingServiceImpl.java relevant code
private final Connection connect() {
String driver = "com.mysql.jdbc.Driver";
String dblink = "jdbc:mysql://localhost:3306/";
String dbname = "gwttest";
String dbuser = "user";
String dbpass = "test";
try {
Class.forName(driver).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection conn = null;
try {
conn = DriverManager.getConnection(dblink + dbname, dbuser, dbpass);
} catch (SQLException e) {
System.err.println("mysql connection error: ");
e.printStackTrace();
}
return conn;
}
here is my helloserver.java relevant code
Button b = new Button("test");
vPanel.add(b);
b.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
GreetingServiceAsync testservice= (GreetingServiceAsync) GWT.create(GreetingService.class);
testservice.echo("test", new AsyncCallback<String>() {
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
vPanel.add(new Label("error"));
//vPanel.add(new Label(caught.printStackTrace());
caught.printStackTrace();
}
#Override
public void onSuccess(String result) {
// TODO Auto-generated method stub
vPanel.add(new Label(result));
}
});
}
});
here is the error message I've recieved upon running and clicking the button (besides the "error" which pops up in my html)
com.google.gwt.user.client.rpc.StatusCodeException: 404 <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 404 NOT_FOUND</title>
</head>
<body><h2>HTTP ERROR: 404</h2><pre>NOT_FOUND</pre>
<p>RequestURI=/helloserver/greet</p><p><i><small>Powered by Jetty://</small></i></p><br/>
</body>
</html>
at com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter.onResponseReceived(RequestCallbackAdapter.java:209)
at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:287)
at com.google.gwt.http.client.RequestBuilder$1.onReadyStateChange(RequestBuilder.java:395)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:338)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:219)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:279)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:242)
at sun.reflect.GeneratedMethodAccessor23.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Unknown Source)
The error is indicating a problem with the RPC. Database connection problems should cause an exception to be serialized to the client, not give a 404. Check that the web.xml and servlet are configured correctly. See: https://developers.google.com/web-toolkit/doc/latest/tutorial/RPC.
If there were any JDBC errors, then they should be visible in the DevMode window, or in the server's log directory if running on a server. It looks like the GreetingServiceImpl class isn't reached at all though so there won't see anything there.
It may be easier to extract the JDBC code to a separate class, and test it separately from GWT. Get one thing working before combining everything together. Run it via a main method, or JUnit test, then you know whether the problem is with the JDBC code or elsewhere.

Apache Derby: SQLSyntaxErrorException

Please have a look at the following code
package normal;
//This class if s for checking the database. If the database doesn't exists, this class will create one
import java.sql.*;
public class DatabaseCheck
{
private Connection con;
public DatabaseCheck()
{
createConnection();
try
{
Statement st = con.createStatement();
st.executeQuery("select * from PhoneData");
}
catch(Exception e)
{
System.out.println(e.getLocalizedMessage());
if(e.getLocalizedMessage().equals("Schema 'SA' does not exist"))
{
try
{
PreparedStatement ps = con.prepareStatement("create table PhoneData(ids int identity constraint pkId primary key,names varchar(20),mobileNumber1 varchar(20),mobileNumber2 varchar(20),landNumber1 varchar(20),landNumber2 varchar(20),address varchar(100),category varchar(20),nickName varchar(20),email varchar(20),middleName varchar(20),lastName varchar(20),city varchar(20),country varchar(20))");
ps.execute();
PreparedStatement ps2 = con.prepareStatement("create table Emails(accountType varchar(10) constraint pk_user primary key,userName varchar(50) ,passwords varchar(50))");
ps2.execute();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
}
finally
{
closeConnection();
}
}
public void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection("jdbc:derby:PhoneBook;create=true","sa","sasasa");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void closeConnection()
{
try
{
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This class is capable of programmatically creating tables in embedded apache derby database. But, it gives the following error
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "identity" at line 1, column 32.
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement20.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement30.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement40.<init>(Unknown Source)
at org.apache.derby.jdbc.Driver40.newEmbedPreparedStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at normal.DatabaseCheck.<init>(DatabaseCheck.java:27)
at normal.MyPhoneBookApp.main(MyPhoneBookApp.java:25)
Caused by: java.sql.SQLException: Syntax error: Encountered "identity" at line 1, column 32.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 15 more
Caused by: ERROR 42X01: Syntax error: Encountered "identity" at line 1, column 32.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.sql.compile.ParserImpl.parseStatement(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
... 9 more
When I remove the "identity" keyword from the table creation code, this work fine. But, auto generation of ID's is mandatory. Please help!
Derby has no identity column type (as documented in the manual). You need to define a generated column. For the generation definition, Derby indeed knows an identity attribute, but that's not a datatype.
So the column definition for ids should be
ids integer generated always as identity constraint pkId primary key
Note that you can also use generated by default instead of always. Then a value will only be generated if you don't specify a value for that column during insert. generated always will overwrite any value you provide.
The Apache Derby documentation indicates you can replace the identity keyword with:
NOT NULL GENERATED ALWAYS AS IDENTITY

Simple Java web service issue

I want to create a webservice in Java that accesses a database stored in an external server. I have created a BeepWebService class containing the main information:
#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;
}
}
I have then created the publisher class, named BeepWebServicePublisher:
public class BeepWebServicePublisher {
public static void main(String[] args){
System.out.println("Web Service initiating...");
Endpoint.publish("http://xxxxxx.ipagemysql.com/", new BeepWebService());
}
}
Unfortunately after compiling successfully the two classes and run the application, the output message is 'failed' (meaning that the connection couldn't be estabilished with the database) followed by an exception error. This is the complete output:
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
As I am a novice in this field, can someone tell me if there is something wrong in the code or the problem may be with the server? Thanks!
Print out the entire stack trace; it'll give you more information than your "failed" message.
Where did you register the MySQL JDBC driver? I don't see it.
UPDATE: I'd recommend that you decompose the problem. Don't put the database code in the web service. Create an interface-based POJO that you can test off line. Get it working, then give an instance to the web service to use.
You have 99 problems, son. Start by fixing one at a time.
This is wrong:
private String db_str = " select Name beep.SW where Name = ";
You need a binding parameter:
private String db_str = " select Name beep.SW where Name = ?";
You need a PreparedStatement, not a Statement.
Then you want to bind the name you pass in.
You only have one column returned by the SELECT; why do you setString on column 2?
Wrong in so many ways.

Categories