I have settings in the context.xml which contain the information for the connection of my database
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<Resource
name="jdbc/*(my username)*"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
auth="Container"
type="javax.sql.DataSource"
removeAbandoned="true"
removeAbandonedTimeout="30"
maxACtive="100"
maxIdle="30"
maxWait="10000"
username= *(my username)*
password= *(my password)*
driverClassName="com.ibm.db2.jcc.DB2Driver"
url="jdbc:db2://(my server host):50000/*(my username)*">
</Resource>
</Context>
While for the Connection Pool I created a class to initiate and to connect it to the database. The error begins in the method of getConnection(). The way the error is NullPointerException in the return of the datasource.getConnection()
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ConnectionPool {
private static ConnectionPool pool = null;
private static DataSource dataSource = null;
private ConnectionPool() {
try {
InitialContext ic = new InitialContext();
dataSource = (DataSource) ic.lookup("java:/comp/env/jdbc/COMPANY");
System.out.print(dataSource);
} catch (NamingException e) {
System.out.println(e);
}
}
public static synchronized ConnectionPool getInstance() {
if (pool == null) {
pool = new ConnectionPool();
}
return pool;
}
public Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
System.out.println(e);
return null;
}
}
public void freeConnection(Connection c) {
try {
c.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}
I tested the database connection with Eclipse's Perspective Database Development and I was able to connect and done all the queries.
In addition, it gives me this error in output
SEVERE: Unable to create initial connections of pool.
java.sql.SQLException: No suitable driver found for jdbc:db2://db2.cecsresearch.org:50000/(my username)
Although I have the jar library files in the lib folder and in the classpath.
Please download the DB2 Java driver from https://artifacts.alfresco.com/nexus/content/repositories/public/com/ibm/db2/jcc/db2jcc4/10.1/db2jcc4-10.1.jar and add it to your tomcat/lib directory. Then restart Tomcat and you should be good to go !!
The nullpointer is simply caused by the following problem:
java.sql.SQLException: No suitable driver found for jdbc:db2://db2.cecsresearch.org:50000/(my username)
Putting your database driver in $CATALINA_HOME/lib should fix the problem.
For more info, check the docs.
driverClassName (String) The fully qualified Java class name of the
JDBC driver to be used. The driver has to be accessible from the same
classloader as tomcat-jdbc.jar
You can also check the official jndi-datasource examples.
Related
I've searched through similar questions and didn't find a solution that worked for me. I'm running following in Netbeans > servlet:
public Connection getConnection()
{
Connection result = null;
BasicDataSource dataSource = getDataSource();
try {
result = dataSource.getConnection();
} catch (SQLException ex) {
Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
}
catch (Throwable e)
{
e.printStackTrace();
}
return result;
}
It works fine when executed in a Java project. Then I added this project's jar as a library to a servlet project in Netbeans - it throws exception:
"java.sql.SQLException: Cannot create JDBC driver of class '' for connect URL 'jdbc:mysql://127.0.0.1:3306/config'"
It looks like this "class ''" thing should point to a class name but where do I get it?
fixed that. had to put drivers into glassfish/lib directory
I have a java project that implements some APIs, in Eclipse.
I have db.java file that enables the communication with the MySQL database.
Instead of have the MySQL credentials in a java file, I would like to have them in /META-INF/context.xml file.
Do you know how to do this?
This is my current code:
public class db {
private String userName = null;
private String password = null;
private String dbName = null;
private String db_connect_string = null;
public db() {
this.db_connect_string = "jdbc:mysql://localhost/mydb";
this.dbName = "name";
this.userName = "uname";
this.password = "pass";
}
protected Connection getDBMySQLCon() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
return DriverManager.getConnection(this.db_connect_string+"?useSSL=false", this.userName, this.password);
} catch (ClassNotFoundException | SQLException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
Instead of an XML file, you can have a properties file, that has the required information. Problem with XML file is that you will have to choose an XML parser and work with it.
If you want to go ahead with properties file you can consider the following snippet.
public void setProp() throws Exception{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
// you can get values you want as properties using
this.db_connect_string = p.getProperty("db_connect_string");
this.dbName = p.getProperty("dbName");
}
And your file structure should be something like
db_connect_string=connection.string
dbName=name
userName=uname
password=pass
This is part of the environment of the container.
/META-INF/context.xml
The context.xml overides the tomcate context entry.
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!-- Specify a JDBC datasource -->
<Resource name="jdbc/mydatabase"
auth="Container"
type="javax.sql.DataSource"
username="YOUR_USERNAME"
password="YOUR_PASSWORD"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://mysql.metawerx.net:3306/YOUR_DATABASE_NAME?
autoReconnect=true"
validationQuery="select 1"
maxActive="10"
maxIdle="4"/>
</Context>
// Get DataSource
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mydatabase");
// Get Connection and Statement
Connection c = ds.getConnection();
Statement s = c.createStatement();
I'm trying to write a class that implements DataSource. This seems simple enough, but the examples I'm seeing for Oracle all declare the class like this:
public class ConnectionPoolingBean implements SessionBean {
....
}
I would expect to see something more like this:
public class MyDataSource implements DataSource {
....
}
Also, I don't understand how the connection is actually working. The getConnection() method only takes the arguments for username and password. So how am I connecting to my database?
Ultimately, what I need to understand is how do I connect to my database and return a result set from a query using DataSource. I just don't see any clear examples of how write a class to use this on my WebApp.
Here's what I've been reading from, which is now just confusing me.
https://docs.oracle.com/javase/tutorial/jdbc/basics/sqldatasources.html
http://docs.oracle.com/javase/7/docs/api/javax/sql/DataSource.html
Use any connection pool for your use case.If you are using app server you can use app server connection pool or use opensource dbcp connection pool mechanism.
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
Example
import org.apache.commons.dbcp2.BasicDataSource;
public class DataBaseUtility
{
private static BasicDataSource dataSource;
private static BasicDataSource getDataSource()
{
if (dataSource == null)
{
BasicDataSource ds = new BasicDataSource();
ds.setUrl("jdbc:mysql://localhost/test");
ds.setUsername("root");
ds.setPassword("password");
ds.setMinIdle(5);
ds.setMaxIdle(10);
ds.setMaxOpenPreparedStatements(100);
dataSource = ds;
}
return dataSource;
}
public static void main(String[] args) throws SQLException
{
try (BasicDataSource dataSource = DataBaseUtility.getDataSource();
Connection connection = dataSource.getConnection();
PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM account");)
{
System.out.println("The Connection Object is of Class: "+connection.getClass());
try (ResultSet resultSet = pstmt.executeQuery();)
{
while (resultSet.next())
{
System.out.println(resultSet.getString(1) + "," + resultSet.getString(2) + "," + resultSet.getString(3));
}
}
catch (Exception e)
{
connection.rollback();
e.printStackTrace();
}
}
}
}
For school they're making us connect to a postgresDB trough plain old dao's and tomcat. However the given code ain't working and I've been stuck here for quite a bit now.
So here goes.
The connectiondao given:
package nl.hu.v1wac.firstapp.persistence;
import java.sql.Connection;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class BaseDao {
protected final Connection getConnection() {
Connection result = null;
try {
InitialContext ic = new InitialContext();
DataSource ds = (DataSource)ic.lookup("java:comp/env/jdbc/PostgresDS");
result = ds.getConnection();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return result;
}
}
We had to write the server specifics into an context.xml file, and import the jar driver into the lib folder of tomcat (so far so good). The context.xml is in the src/main/webapp/META-INF directory
The context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/PostgresDS"
url="jdbc:postgresql://localhost:5432/worlddb"
driverClassName="org.postgresql.Driver"
auth="Container"
type="javax.sql.DataSource"
username="postgres"
password="secret" />
</Context>
After setting up my Dao's, I try to fire them up in a main and get the following error:
Exception in thread "main" java.lang.RuntimeException: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
which is said caused by:
DataSource ds = (DataSource)ic.lookup("java:comp/env/jdbc/PostgresDS");
Would anyone be able to help, as according the slides / manual this should be all to it :/
Thanks in advance!
p.s. we're using tomcat 8.5 and Eclipse Jee Neon
Edited Main class
package nl.hu.v1wac.firstapp.persistence;
import java.sql.SQLException;
public class Pattern {
public static void main(String[] args) {
// TODO Auto-generated method stub
CountryDao cdao = new CountryDaoPostgreSQL();
try {
cdao.findALl();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You certainly shouldn't be getting that.
You're running this code within Tomcat proper? Not outside? The complaint is that the InitialContext doesn't have the underlying "plumbing" to do the lookup. Normally this is all managed by the environment that you're running in, unless you're running it "stand alone" in a Java SE app, you should never see this.
So this is my thing. I am trying to connect do MySQL Database from java. I have downloaded connector driver from MySQL ( Its called "mysql-connector-java-5.0.8-bin.jar" ) and I added to my libraries (Im using NetBeans). I tried to do simple connection like this:
package datacon;
public class Datacon {
public static void main(String[] args) {
try {
java.sql.Connection con = (java.sql.Connection) java.sql.DriverManager
.getConnection("jdbc:mysql://localhost:3306/test"
/*, "root"
, "root" */ );
} catch ( Exception e ) {
System.out.println( e.toString() );
}
}
}
But this hapened:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
I made my research on the internet and this pretty common thing, but none of the answers helped me. I was able connect to database through NetBeans/services, so that URL jdbc:mysql://localhost:3306/test should be correct.
I am using:
java: Oracle java SDK 1.7.0 _ 45
IDE: NetBeans 7.4
OS: Debian 3.2.51-1 x86_64
Driver: MySQL Connector/J 5.0.8
I am afraid this is gonna have a very trivial answer, but I am stuck here for a while now and i need to move. So what am I missing?
Add:
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (final ClassNotFoundException e) {
e.printStackTrace();
}
}
I thing you forget to load driver .
Class.forName("com.mysql.jdbc.Driver");
and make sure you have mysql-connector-java-5.1.22-bin in your class path.
try {
Class.forName("org.gjt.mm.mysql.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
try {
class.forname("com.mysql.jdbc.Driver");
driver.getconnection("connenctionurl","name","password");
Statement s =goodrecive.asif().createStatement();
s.executeUpdate("INSERT INTO product(productno,productname,quantity,ammount)values('"+t1.getText()+"','"+t2.getText()+"','"+t3.getText()+"','"+t4.getText()+"')");
} catch (Exception e) {
System.out.println(e);
}
}
My class for connection:
package connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionFactory {
public Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/<database>", "<user>", "<password>");
}
}
Don't need add ClassForName. This is necessary in older versions of java.