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.
Related
I have a JAR file that doesn't connect to the database even though it connects just fine in the IDE. I'm stuck and I don't know where to go from here. I am using Java 8 in IntelliJ trying to run SQLite.
Here is the code for the Database class.
private static Connection connection = null;
private static boolean connected = false;
static void connect() {
String driver = "org.sqlite.JDBC";
String db = "schedulerDB";
String path = "lib\\";
String url = "jdbc:sqlite:";
try {
Class.forName(driver);
connection = DriverManager.getConnection(url + path + db);
printInfo("Connected to database : " + db);
connected = true;
} catch (SQLException e) {
printError(1100, "Could not connect to database", e);
} catch (ClassNotFoundException e) {
printError(1101, "Driver not found error", e);
}
}
When I run the JAR file in the terminal, I get:
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: user)
Please help me.
Added e.printStackTrace(); as requested:
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: user)
at org.sqlite.core.DB.newSQLException(DB.java:941)
at org.sqlite.core.DB.newSQLException(DB.java:953)
at org.sqlite.core.DB.throwex(DB.java:918)
at org.sqlite.core.NativeDB.prepare_utf8(Native Method)
at org.sqlite.core.NativeDB.prepare(NativeDB.java:134)
at org.sqlite.core.DB.prepare(DB.java:257)
at org.sqlite.jdbc3.JDBC3Statement.execute(JDBC3Statement.java:52)
at scheduler.Database.query(Database.java:337)
at scheduler.User.buildList(User.java:42)
at scheduler.User.<clinit>(User.java:85)
at scheduler.Main.start(Main.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
at java.lang.Thread.run(Unknown Source)
Change the value of url to
url = "jdbc:sqlite::resource:"
Your exception is actually caused by a MalformedURLException. The reason you are getting this is because lib\schedulerDB is not a valid URL.
URLs must use forward slashes (/), on all systems—even Windows. This is a requirement of the URI specification itself. (A URL is a type of URI, so every URL must conform to the rules of a URI.)
Making your URL valid should do the trick:
String path = "lib/";
I downloaded and installed the uCanAccess jars by following instructions from here:
Manipulating an Access database from Java without ODBC
I'm learning how to use the microsoft access db for java and this is the coding I used
package Main.Net;
import java.sql.*;
public class DataBase {
Connection con;
Statement st;
ResultSet rs;
public DataBase() {
}
private void connect() {
try {
//String driver = "sun.jdbc.odbc.jdbcodbcdriver";
//Class.forName(driver);
String db = "jdbc:ucanaccess://C:/Users/MyUser/workspace/Connectors_DB.accdb";
con = DriverManager.getConnection(db);
st = con.createStatement();
String sql = "select * from Table";
rs = st.executeQuery(sql);
while(rs.next()) {
String username = rs.getString("Username");
String password = rs.getString("Password");
System.out.println(username + "\t" + password);
}
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new DataBase().connect();
}
}
and when I run the java program, it comes with this error
Exception in thread "main" java.lang.NoSuchMethodError: org.hsqldb.DatabaseURL.parseURL(Ljava/lang/String;ZZ)Lorg/hsqldb/persist/HsqlProperties;
at org.hsqldb.jdbc.JDBCDriver.getConnection(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at net.ucanaccess.jdbc.DBReference.getHSQLDBConnection(DBReference.java:354)
at net.ucanaccess.jdbc.UcanaccessDriver.connect(UcanaccessDriver.java:206)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Main.Net.DataBase.connect(DataBase.java:23)
at Main.Net.DataBase.main(DataBase.java:42)
error is at this code:
String db = "jdbc:ucanaccess://C:/Users/MyUser/workspace/Connectors_DB.accdb";
con = DriverManager.getConnection(db);
does it have something to do with the version of the hsqldb? because if it does I already tried downloading other versions of hsqldb and the same error appears
here are the jars I'm using:
ucanaccess-2.0.9.3.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.0.8.jar
so... how can I fix this?
The answers in this thread suggest, that there are multiple hsqldb-versions on your classpath. Maybe one of the other involved jars contains hsqldb as well? You can inspect them using a zip tool of your choice, or the command jar -tf foo.jar.
I’m new using IntelliJ 13 and I have a problem on connection to MySQL. I’m using the code as below and this code I learn from tutorials Manage Your Database Scheme with IntelliJ IDEA 12.
public class App {
public static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
public static final String JDBC_URL = "jdbc:mysql://localhost/sample";
public static final String JDBC_USER = "root";
public static final String JDBC_PASSWORD = "";
public static void main (String[] args) throws SQLException, ClassNotFoundException {
Statement statement = null;
try{
Class.forName(JDBC_DRIVER);
Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select id, firstname, lastname, email " +
"from customer");
System.out.println("First name\tLast name\tEmail");
int count = 0;
while (resultSet.next()){
String firstname = resultSet.getString("firstname");
String lastname = resultSet.getString("lastname");
String email = resultSet.getString("email");
System.out.printf("%s\t%s\t%s%n", firstname, lastname, email);
count++;
}
System.out.println("--");
System.out.println(MessageFormat.format("Rows: {0}", count));
} finally {
if(statement != null){
statement.close();
}
}
}
}
I have tried many solution based on this issue on https://stackoverflow.com/ but nothing can solved my problem.
It give error message like this
Connection to MySQL – sample#localhost failed: Exception in thread “main” java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at com.intellij.persistence.database.console.RemoteJdbcServer.main(RemoteJdbcServer.java:15)
I've followed this as well to solve my problem, but nothing works to me even the problem is same.
http://nixmash.com/java/classnotfoundexception-com-mysql-jdbc-driver-fix-in-intellij-idea/. Actually, I want to create database using MySQL on IntelliJ 13 but the connection to MySQL is failed. I have tried to solve this problem with putting mysql-connector-java-5.1.26-bin.jar in project structure, but it's not work for me. I don't know how to solve this problem? I hope some experts on this issue will help me some ways to solve this problem.
I cannot use the comment, I don't know why. So I reply the answer here. Ashish: I already download the jar files, but I don't know where to put that files. Do you have idea?
You need to download jar containing com.mysql.jdbc.Driver .
So you can Download jar from here and then set your classpath.
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.
I have written sql server connection part.When I run this code, i got this error.
Error Trace in getConnection() : com.microsoft.jdbc.sqlserver.SQLServerDriver
Error: No active Connection
java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.sample.DB.getConnection(DB.java:30)
at com.sample.DB.displayDbProperties(DB.java:49)
at com.sample.DB.main(DB.java:85)
I have installed sql sever 2008 R2. I serached google I couldn't find the solution....
This is my code
public class DB {
private java.sql.Connection con = null;
private final String url = "jdbc:microsoft:sqlserver://";
private final String serverName= "localhost";
private final String portNumber = "1433";
private final String databaseName= "XONTHOMass_User";
private final String userName = "sa";
private final String password = "xont#123";
// Informs the driver to use server a side-cursor,
// which permits more than one active statement
// on a connection.
private final String selectMethod = "cursor";
private String getConnectionUrl(){
return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
}
private java.sql.Connection getConnection(){
try{
System.out.println("========1========");
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
System.out.println("==== 2=====");
con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
if(con!=null) System.out.println("Connection Successful!");
}catch(Exception e){
e.printStackTrace();
System.out.println("Error Trace in getConnection() : " + e.getMessage());
}
return con;
}
/*
Display the driver properties, database details
*/
public void displayDbProperties(){
java.sql.DatabaseMetaData dm = null;
java.sql.ResultSet rs = null;
try{
con= this.getConnection();
if(con!=null){
dm = con.getMetaData();
System.out.println("Driver Information");
System.out.println("\tDriver Name: "+ dm.getDriverName());
System.out.println("\tDriver Version: "+ dm.getDriverVersion ());
System.out.println("\nDatabase Information ");
System.out.println("\tDatabase Name: "+ dm.getDatabaseProductName());
System.out.println("\tDatabase Version: "+ dm.getDatabaseProductVersion());
System.out.println("Avalilable Catalogs ");
rs = dm.getCatalogs();
while(rs.next()){
System.out.println("\tcatalog: "+ rs.getString(1));
}
rs.close();
rs = null;
closeConnection();
}else System.out.println("Error: No active Connection");
}catch(Exception e){
e.printStackTrace();
}
dm=null;
}
private void closeConnection(){
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
DB myDbTest = new DB();
myDbTest.displayDbProperties();
}
}
Please help me..I did this application using the eclipse.I have put jar file also `sqljdbc4.jar'...
Please help me
You receive the exception:
java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriver
That means your program cannot find the Driver and therefore not even try to connect to the database.
Mircosoft has an article on How to Get Started with Microsoft JDBC:
The Microsoft SQL Server 2000 driver for JDBC .jar files must be listed in your CLASSPATH variable. The CLASSPATH variable is the search string that Java Virtual Machine (JVM) uses to locate the JDBC drivers on your computer..
As a complete guess, you have installed Express Edition (you should always mention the edition, not just the version) but you have not enabled TCP/IP support using the SQL Server Configuration Manager. By default, Express Edition does not have any network protocols enabled, so connecting over TCP/IP will not work unless you enable it first.
I think this is the driver that you need to use
com.microsoft.sqlserver.jdbc.SQLServerDriver
not com.microsoft.jdbc.sqlserver.SQLServerDriver
Just do one thing go to http://www.java2s.com/Code/Jar/s/Downloadsqljdbcjar.htm and download the sqljdbc jar and use it in your program.