I have created a Dynamic Web Page project in Eclipse and coded a Servlet. I have added derby.jar as a library. When I'm going to deploy the project, I export it as a .war-file and then start Jetty with java -jar start.jar. The servlet works fine without database code. But when I try to use the JavaDB database, the JDBC driver couldn't be found. How do I use a JavaDB database from my Servlet in Jetty?
I try to use an in-memory-database for testing, and my code looks like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String sql = "DECLARE GLOBAL TEMPORARY TABLE SESSION.mytable "+
"(id int, message varchar(10)) NOT LOGGED";
String connURL = "jdbc:derby:memory:memdatabase;create=true";
try {
Connection conn = DriverManager.getConnection(connURL);
PreparedStatement ps = conn.prepareStatement(sql);
boolean success = ps.execute();
System.out.println("created: " + success);
} catch (SQLException e) {
e.printStackTrace();
}
}
Here is the Exception that is thrown:
java.sql.SQLException: No suitable driver found for jdbc:derby:memory:memdatabas
e;create=true
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.example.MyJavaServlet.doPost(MyJavaServlet.java:59)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:598
)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java
:486)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.j
ava:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.jav
a:499)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandl
er.java:233)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandl
er.java:1065)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:
413)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandle
r.java:192)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandle
r.java:999)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.j
ava:117)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(Cont
extHandlerCollection.java:250)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerColl
ection.java:149)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper
.java:111)
at org.eclipse.jetty.server.Server.handle(Server.java:350)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(Abstrac
tHttpConnection.java:454)
at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpC
onnection.java:900)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.conten
t(AbstractHttpConnection.java:954)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:851)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnecti
on.java:77)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEn
dPoint.java:606)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEnd
Point.java:46)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPoo
l.java:603)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool
.java:538)
at java.lang.Thread.run(Unknown Source)
You did not load the driver class before obtaining a connection:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection conn = ...
Just as a side note, you might also want to refactor the process of loading the driver class and using connections to a single point in your application.
Related
I was trying to connect to MySQL "twitch" database using java with this code below:
import java.sql.*;
public class App {
public static void main(String[] args) throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
//Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc://localhost:3306/twitch";
String username = "root";
String pass = "nfreal-yt10";
Connection con=DriverManager.getConnection(url,username,pass);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select distinct creator_id from twitch.information where creator_id > 40;");
while (rs.next()) {
System.out.println(rs.getString(1));
}
con.close();
}
catch(Exception e) {
System.out.println(e);
}
}
}
when I executed the code my console throws (Full error):
Loading class `com.mysql.jdbc.Driver'.
This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver
class is generally unnecessary.
java.sql.SQLException: No suitable driver found for jdbc://localhost:3306/twitch
I have added MySQL connector on my directory folder and all stuff which required to be added, yet the error still occurred, why?
When you communicate with your database (located at /localhost:3306/twitch), you must precise the protocol used (eg. your browser use http or https protocol followed with the adress).
JDBC is a driver that can interface with MySQL, but can't directly access to your database. Hence your URL should be:
String url = "jdbc:mysql://localhost:3306/twitch";
EDIT : Class.forName("com.mysql.cj.jdbc.Driver"); is no more needed in general. Details here.
I try to insert data into MySQL using Java and I have error all the time.
I use this video to understand how to do to the connection.
This is my Java code:
import java.sql.*;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection conn = null;
//DriverManager.registerDriver(new com.mysql.jdbc.Driver ());
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/try1-progrem", "root", "123456");
Statement st = conn.createStatement();
String username = "kola";
String password = "24688642";
String insert = "INSERT INTO login VALUES ('"+username+"','"+password+"')";
st.executeUpdate(insert);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Get the error:
java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost:3306/try1-progrem
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Main.main(Main.java:11)
And here to SQL image: sql data:
** I learned from YouTube how to make the connection, if there is a good guild, I will glad to take him.
*EDIT1:
build
To fix this you should follow the steps below:
You need to download the correct ConnectorJ from the link below.
After downloading the correct installer for your machine you will need to run the installer to install only the correct jdbc connector for you. (A series of prompts will lead you to selecting the connector and not all the MySQL downloads)
Then you can put the .jar file (connectorJDBC file) into your classpath appropriately and this should fix your problem as I encountered a similar problem while trying to connect to a SQL server with java.
Hopefully this fixes your problem, comment if it doesn't. :)
ConnectorJ Download
Iam Using Glassfish 3 server to run a web service.
Connection Pool is implemented in the server and able to ping Database.
Connection is received from the server but it is throwing java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended exception while running PreparedStatement.
Glassfish 4 does not throw any exception
The Query is taken from property file
QUERY=select * from TABLE where SYSTEMID=?1
Using two seperate java classes for receiving connection and further processing
JDBCUtil.java
public static Connection connectionFromConnectionPool()
throws NamingException, SQLException {
Context initCtx = new InitialContext();
DataSource dataSource = (DataSource) initCtx.lookup(PropertyFileReader
.getPropertyValue("connectionPool.JNDI.name"));
Connection connection = (Connection) dataSource.getConnection();
if (connection != null) {
logger.info("Received Connection");
} else {
logger.info("No Connection Received");
}
return connection;
}
DAO.java
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
try {
connection = JDBCUtil.connectionFromConnectionPool();
if (connection != null) {
preparedStatement = connection
.prepareStatement(PropertyFileReader
.getPropertyValue("QUERY"));
if (preparedStatement != null) {
preparedStatement.setString(1, "systemID");
resultSet = preparedStatement.executeQuery(); // line No:56
Log generated :
18:13:35,328 INFO - *****.JDBCUtil.connectionFromConnectionPool(JDBCUtil.java:38) - Received Connection
18:13:35,397ERROR - *****(DAO.java:81) - **************************** ::
java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:440)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:837)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:445)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:863)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1153)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1275)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3576)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3620)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1491)
at com.sun.gjc.spi.jdbc40.PreparedStatementWrapper40.executeQuery(PreparedStatementWrapper40.java:642)
at *************************************(DAO.java:56)
....................
ojdbc6.jar placed in glassfish3\glassfish\lib and glassfish4\glassfish\lib
Check if there is any other ojdbc jar inside server folder especially inside domain folder you are using.
If there are different jars or different versions of jar in the server folder, it may cause such errors.
For ex : glassfish3\glassfish\domains\domain1\lib...
If there are jar files of different versions, replace them all with same version.
I use Glassfish4. I kept the ojdbc jar only in glassfish4\glassfish\lib which works fine for me.
I'm doing an app for my high school and I have the following situation:
I will use an embedded HSQL database for storing my application data. When I open the connection, I try to connect to the database only if exists, so it will not be created if it doesn't exist. Basically, if an HsqlException is thrown, functions to create the database, tables and constraints will be called.
The point is that this line:
Connection c = DriverManager.getConnection(url, user, pwd);
Throws an SQLException AND an HsqlException. But if I try to catch and control them, the output keeps being like this:
run:
2014-11-19T20:15:25.142+0100 SEVERE could not reopen database
Catched an Hsql or SQL Exception. //This is my 'control' over the Exceptions.
org.hsqldb.HsqlException: La base de datos no existe: C:/Databases/DB
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.persist.Logger.open(Unknown Source)
at org.hsqldb.Database.reopen(Unknown Source)
at org.hsqldb.Database.open(Unknown Source)
at org.hsqldb.DatabaseManager.getDatabase(Unknown Source)
at org.hsqldb.DatabaseManager.newSession(Unknown Source)
at org.hsqldb.jdbc.JDBCConnection.<init>(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.getConnection(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at DBManager.DBManager.main(DBManager.java:20)
BUILD SUCCESSFUL (total time: 0 seconds)
And finally this is my code. I hope someone call tell me why is this happening.
package DBManager;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DBManager {
static Connection c;
static Statement stm;
public static void main(String[] args){
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
c = DriverManager.getConnection("jdbc:hsqldb:file:C:/Databases/DB;create=false", "SA", "");
} catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException has been catched.");
} catch (SQLException | org.hsqldb.HsqlException ex) {
System.out.println("Catched an Hsql or SQL Exception.");
//TODO call connection where the database is created.
//TODO create schema CreateSchema.run(c);
//TODO create constraints
} finally {
//TODO
}
}
private static class CreateSchema{
public static void run(Connection con){
//TODO: Create table queries.
}
}
}
Assuming you do not already have a HSQLDB database in C:/Databases/DB then this is behaving how I would expect. Your connection string tells it not to create the database if it does not exist, so it can't return an exception so it throws an exception which you are catching and logging.
Because the exception has been caught the run is considered successful because the main method did not throw an exception or call System.exit() with a non-zero value.
The exception you are catching is actually the SQLException and not the HsqlException (which is a RuntimeException) - the SQLException has a nested HsqlException. If you print the stack trace of the exception (ex.printStackTrace()) you can see this. So you should just catch SQLException.
The extra output you see is from within the HSQLDB driver class - if you look at the source for org.hsqldb.Database#reopen() you can see it calls logger.logSevereEvent("could not reopen database", e); and that's what responsible for the extra output you see. It tries to use a logging framework if one is available and defaults to the one in the JDK, which if not configured will print to System.err.
I am having this error on Netbeans 7.2, it says that ClassNotFoundexception and InstantationException. I am really stuck on this matter. Kindly help me.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String driver = "com.mysql.jdbc.Driver";
con = null;
String username = "";
String password = "";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName", "root", "password");
Statement st = con.createStatement();
ResultSet mar = st.executeQuery("SELECT * FROM table");
Gson gson = new GsonBuilder().create();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
} catch (SQLException e) {
String message = e.getMessage();
}
What about this simple way?!
java.sql.Driver d=new com.mysql.jdbc.Driver();
I also wondered why do you connect to database with such this way?! It's better let server manage it.
First config the context.xml (if you are using tomcat) like this:
<context>
<Resource name="_ds" auth="Container" type="javax.sql.DataSource"
maxActive="128" maxIdle="32" username="_admin" password="qwerty" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/dbname"/>
</context>
Then, simple get a connection from this resource in servlet/etc, like this:
public void init() {
try {
_ds = (DataSource) InitialContext.lookup("java:/comp/env/_ds");
} catch (Exception ex) {
}
}
private javax.sql.DataSource _ds;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try {
/*String driver = "com.mysql.jdbc.Driver";
con = null;
String username = "";
String password = "";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName", "root", "password");*/
Connection con=_ds.getConnection();
Statement st = con.createStatement();
ResultSet mar = st.executeQuery("SELECT * FROM table");
Gson gson = new GsonBuilder().create();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
con.close();
} catch (SQLException e) {
String message = e.getMessage();
}
By the way, don't forget to compy the MySQL JDBC driver jar-file in <CATALINA_BASE>/lib folder.
All you need is Class.forName("com.mysql.jdbc.Driver")
This acts like class loader and load your driver class for you. For that you need to add the corresponding jar file(which has the driver implementation). So download and add mysql-connector.jar in your class path.
Note : If you are using Java 7 then there is no need to even add the Class.forName("com.mysql.jdbc.Driver") statement.Automatic Resource Management (ARM) is added in JDBC 4.1 which comes by default in Java 7.
You might want to solve a bigger problem. You ought not enter configuration data such as database connection information directly in your servlet.
Are you using Tomcat? You can simply use JNDI. You will be able to change database details and drivers without having to recompile your servlet.
Here is the Tomcat 7.0 JNDI Datasource HOW-TO shows various ways in which you can get a Connection to your database.
On that page, you have a code example of how to get a Connection (Oracle 8i, 9i & 10g -> Part 3), and how to write a MySQL specific configuration.
Make sure to download a correct MySQL jar and place it in your Tomcat's lib/ directory (or alternatively your WAR's WEB-INF/lib).
You need to add mysqlconnector.jar file found here: ( http://dev.mysql.com/downloads/connector/j/ ) into your lib folder of your project. Include it with your project and then you can access your connection with database.
Add that jar into the buildpath.