why does the javax.naming.NamingException occur here? - java

when i run the following :
package NonServletFiles;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.sql.DataSource;
import javax.naming.*;
public class GetTagsFromDatabase {
public GetTagsFromDatabase() {
}
public String[] getTags() {
String tags[] = null;
try {
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/photog"); // <<----- line 23
Connection connection = ds.getConnection();
String sqlQuery = "select NAMEOFTHETAG from tagcollection";
PreparedStatement statement = connection.prepareStatement(sqlQuery);
ResultSet set = statement.executeQuery();
int i = 0;
while(set.next()) {
tags[i] = set.getString("NameOfTheTag");
System.out.println(tags[i]);
i++;
}
}catch(Exception exc) {
exc.printStackTrace();
}
return tags;
}
public static void main(String args[]) {
new GetTagsFromDatabase().getTags(); // <<----- line 43
}
}
I get the following exceptions :
javax.naming.NamingException: Lookup failed for 'java:comp/env/jdbc/photog' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.url.pkgs=com.sun.enterprise.naming, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl} [Root exception is javax.naming.NamingException: Invocation exception: Got null ComponentInvocation ]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:518)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at NonServletFiles.GetTagsFromDatabase.getTags(GetTagsFromDatabase.java:23)
at NonServletFiles.GetTagsFromDatabase.main(GetTagsFromDatabase.java:43)
Caused by: javax.naming.NamingException: Invocation exception: Got null ComponentInvocation
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.getComponentId(GlassfishNamingManagerImpl.java:873)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:742)
at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:172)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:498)
... 4 more
I don't know the reason for this exception,all other servlets that need to connect to the database with the url java:comp/env/jdbc/photog work fine.

The stacktrace hints that you're using Glassfish. Remove the java:comp/env/ part. It's the default JNDI context root already. Only in Tomcat you need to specify it explicitly. Also, you should be invoking this in webapp context, not as a plain Java Application with main().
Unrelated to the concrete problem, do you really need to get the DataSource everytime? I'd create a helper class which obtains it only once on webapp's startup or in a static initializer. It's application wide and threadsafe. Only the Connection indeed needs to be obtained (and closed! you're not closing it, so you're leaking DB resources) everytime you need to fire a SQL query.

Related

Jdbc:Connection is returning null in my program what to do? [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 1 year ago.
am getting an exception as java.sql.Connection.prepareStatement(String) because con is null, I don't know why as I have already added MySQL Connector jar file.
import java.sql.Connection;
import java.sql.PreparedStatement;
public class Studentdao {
public static boolean insertStudenttoDB(Student st) {
boolean f=false;
try {
Connection con =CP.createc();
//jdbc code
String q="insert into students(sname,sphone scity)values(?,?,?)";
PreparedStatement pstmt=con.prepareStatement(q);
pstmt.setString(1,st.getStudentname());
pstmt.setString(2,st.getStudentcity());
pstmt.setLong(3,st.getStudentphone());
//execute
pstmt.executeUpdate();
f=true;
}
catch(Exception e) {
e.printStackTrace();
}
return f;
}
}
This is my connection program
import java.sql.Connection;
import java.sql.DriverManager;
public class CP {
static Connection con;
//load driver
public static Connection createc() {
try {
Class.forName("com.sql.jdbc.Driver");
//creating connection
String user="mysql";
String password="mysql";
String url="jdbc:mysql://localhost:3306/student_manage";
con=DriverManager.getConnection(url,user,password);
}catch(Exception e) {
e.printStackTrace();
}
return con;
}
}
Incorrect class name
You appear to have an incorrect class name, if you are using the Connector/J product as your JDBC driver.
Section 3.6.1 of the Connector/J manual shows the use of "com.mysql.cj.jdbc.Driver" versus your use of "com.sql.jdbc.Driver". Here is their code example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Notice, do not import com.mysql.cj.jdbc.*
// or you will have problems!
public class LoadDriver {
public static void main(String[] args) {
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
}
}
DataSource
Note that your use of Class.forName is generally not needed in modern Java. The JDBC architecture was years ago revamped so that now drivers are automatically located and loaded using the Java Service Provider Interface (SPI) technology.
I do suggest you make a habit of using a DataSource to obtain connections rather than calling on the DriverManager. Using DataSource makes your code much more flexible. You will be able to switch JDBC drivers, add connection pooling, and externalize configuration info (server address, database name, user name, password, etc.) for deployment.
Usually your JDBC driver comes with a basic implementation of DataSource. Check the documentation for all the various options you can set, specific to your database (MySQL in this case).
For MySQL, I understand the implementation of DataSource currently provided in Connector/J is com.mysql.cj.jdbc.MysqlDataSource. Caveat: I make regular use of Postgres & H2, not MySQL, so I may not be up-to-date.
See my Answer to another Question for source code of a full example of connecting and working with MySQL. Here are the parts relating to DataSource and Connection.
private DataSource configureDataSource ( )
{
System.out.println( "INFO - `configureDataSource` method. " + Instant.now() );
com.mysql.cj.jdbc.MysqlDataSource dataSource = Objects.requireNonNull( new com.mysql.cj.jdbc.MysqlDataSource() ); // Implementation of `DataSource` bundled with H2.
dataSource.setServerName( "db-mysql-sfo3-422-do-user-8982-1.x.db.ondigitalocean.com" );
dataSource.setPortNumber( 24_090 );
dataSource.setDatabaseName( "defaultdb" );
dataSource.setUser( "scott" );
dataSource.setPassword( "tiger" );
return dataSource;
}
Early in the lifecycle of your app, instantiate and retain the DataSource object returned from that method. Remember, a DataSource holds only the configuration details; it is not an open resource itself, and need not be closed.
DataSource dataSource = this.configureDataSource();
To open a connection, pass the DataSource to your method that wants to connect to the database.
private void dumpTable ( DataSource dataSource ) { … }
Here is a piece of that dumpTable method.
Notice the use of try-with-resources syntax to automatically close the open resources in the order in which they were declared, even in case of failure with exceptions being thrown.
String sql = "SELECT * FROM event_ ;";
try (
Connection conn = dataSource.getConnection() ; // 🡄 Use the passed `DataSource` object to ask for a `Connection` object.
Statement stmt = conn.createStatement() ;
ResultSet rs = stmt.executeQuery( sql ) ;
)
{
…
}
catch ( SQLException e )
{
e.printStackTrace();
}
here's the code I tried to connect java class with mysql. Make sure you have to add the required driver to your libraries.
import java.sql.Connection;
import java.sql.DriverManager;
public class Server {
public static Connection getConnection()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
String urls = "127.0.0.1";//you can even replace this with localhost
String username = "yourusername";
String password = "1234";
Connection conn = DriverManager.getConnection("jdbc:mysql://"+urls+":3306/yourdb?useUnicode=yes&characterEncoding=UTF-8", username, password);
return conn;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}

Cassandra QueryLogger introduces NoHostAvailableException

I have a spring boot application, where I have used the pattern of extending AbstractCassandraConfiguration to bootstrap Cassandra. It alls works beautifully. I now want to turn on query logging, so i have attempted to implement this pattern:
https://github.com/spring-projects/spring-boot/issues/7312#issuecomment-358448437
I do this by updating my AbstractCassandraConfiguration implementation to:
1. Be a #Configuration class
2. Adding the Bean QueryLogger Bean
But then at runtime, I start getting the NoHostAvailableException.
As the before and after code are v similar, ill just paste it all and indicate the new, breaking code.
I can feel connection is getting corrupted, but also feel my pattern is so standard, not sure what is going on!!! Any tips appreciated. Thanks
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.config.SchemaAction;
import com.datastax.driver.core.AuthProvider;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.PlainTextAuthProvider;
import com.datastax.driver.core.QueryLogger;
#Configuration // **** NEW ****
public class CassandraConfig extends AbstractCassandraConfiguration {
#Value("${spring.data.cassandra.contact-points:placeholder}")
private String contactPoints;
#Value("${spring.data.cassandra.port:0000}")
private int port;
#Value("${spring.data.cassandra.keyspace-name:placeholder}")
private String keySpace;
#Value("${spring.data.cassandra.username}")
private String username;
#Value("${spring.data.cassandra.password}")
private String password;
#Value("${spring.data.cassandra.schema-action}")
private String schemaAction;
// removed all the #Override getters for above props
// **** NEW ****
#Bean
public QueryLogger queryLogger(Cluster cluster) {
QueryLogger queryLogger = QueryLogger.builder().build();
cluster.register(queryLogger);
return queryLogger;
}
}
Exception:
[dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.cassandra.CassandraConnectionFailureException: Query; CQL [SELECT * FROM my_table;]; All host(s) tried for query failed (tried: cassandradb01.AAA.test.XXXX.com/10.18.51.15:9042 (com.datastax.driver.core.exceptions.BusyPoolException: [cassandradb01.AAA.test.XXXX.com/10.18.51.15] Pool is busy (no available connection and timed out after 5000 MILLISECONDS))); nested exception is com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: cassandradb01.AAA.test.XXXX.com/10.18.51.15:9042 (com.datastax.driver.core.exceptions.BusyPoolException: [cassandradb01.AAA.test.XXXX.com/10.18.51.15] Pool is busy (no available connection and timed out after 5000 MILLISECONDS)))] with root cause

After updating the connection details to MariaDB, system throws ClassNotFoundException

I was advised by my web hosting company to change the 'mysql jdbc connection' details to 'mariadb' as per below in the getDBConnection().
I have downloaded the MariaDB jar [mariadb-java-client-1.7.4.jar] compatible for JDK 1.7 & added jar to the project.
Removed the existing MySQL jar [mysql-connector-java-5.1.40-bin.jar] to avoid any conflict. Clean and build the solution and restarted the tomcat server. While submitting the data system still throws below error. Also while debugging at this point, I am receiving null here connection = SoccerUtils.getDBConnection(); preparedStatement1 = connection.prepareStatement("insert into mydatabase.registeruser values(default,?,?,?,?,?,?,?,?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
Any idea Why this is still throwing ClassNotFoundException: com.mysql.jdbc.Driver ?
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Oct 15, 2018 10:53:57 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [RegisterServlet] in context with path [/MyFirstJavaTest] threw exception
java.lang.NullPointerException
at com.myfirstjavatest.pkg.RegisterServlet.addPlayer(RegisterServlet.java:134)
at com.myfirstjavatest.pkg.RegisterServlet.doPost(RegisterServlet.java:110)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
//Code below:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public static Connection getDBConnection() {
String url = "jdbc:mariadb://localhost:3307/";
String dbName = "mydatabase";
String driver = "org.mariadb.jdbc.Driver";
String userName = "root";
String password = "mypassword";
Connection conn = null;
try {
Class.forName(driver).newInstance();
conn = DriverManager
.getConnection(url + dbName, userName, password);
} catch (Exception e) {
System.out.println(e);
} finally {
}
return conn;
}

Java Class.forName() not working, class string loaded from property file

I have a simple Java project in Eclipse, which can connect to several databases, and am trying to modify it to allow configuration of connection parameters from property file.
At current stage, I have a working DBHelper class, which provides a getDatabaseConnection() method returning a Connection item instantiated using hard coded parameters.
I am trying to create a similar class, which does the same but reads parameters from property file.
It is called PropertyParser and provides getDBConnection() method.
The fact is that Class.forName() method fails if called from this latter, even if all connection data saved in property file are exactly the same hard coded in DBHelper class, and both refer to the full class name (oracle.jdbc.driver.OracleDriver).
Here follows my code.
Old working class:
package mypath.helpers;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBHelper {
public static Connection getDatabaseConnection(){
String dbClass = "oracle.jdbc.driver.OracleDriver";
String dbUrl = "jdbc:oracle:thin:#host:port/service";
String dbUser = "user";
String dbPass = "pass";
// connect to DB
try {
Class.forName(dbClass);
Connection con = DriverManager.getConnection(dbUrl, dbUser, dbPass);
con.setAutoCommit(false);
return con;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
New not working class:
package mypath.helpers;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class PropertyParser extends Properties{
// variables
private static String propFile = "conf/myprops.properties";
private static String dbClassProp = "DBCLASS";
private static String dbUrlProp = "DBURL";
private static String dbUserProp = "DBUSER";
private static String dbPassProp = "DBPASS";
// constructor
public PropertyParser() throws FileNotFoundException, IOException{
super();
this.load(new FileInputStream(propFile));
}
public Connection getDBConnection() throws SQLException, ClassNotFoundException{
// read properties
String JDBCClass = this.getProperty(dbClassProp).trim() ;
String JDBCUrl = this.getProperty(dbUrlProp).trim();
String JDBCUserId = this.getProperty(dbUserProp).trim();
String JDBCPasswd = this.getProperty(dbPassProp).trim();
Class.forName(JDBCClass);
Connection con = DriverManager.getConnection(JDBCUrl, JDBCUserId, JDBCPasswd);
con.setAutoCommit(false);
return con;
}
}
And here's the main, whith both calls:
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException, SQLException {
// this works fine
Connection con = DBHelper.getDatabaseConnection();
System.out.println("Everything works fine till now.");
// this does not work
PropertyParser pp = new PropertyParser();
Connection con2 = pp.getDBConnection();
System.out.println("I will never reach this point.");
}
And here's the output i get:
Everything works fine till now.
Exception in thread "main" java.lang.ClassNotFoundException: "oracle.jdbc.driver.OracleDriver"
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at mypath.helpers.PropertyParser.getDBConnection(PropertyParser.java:35)
at mypath.GetConnection.main(GetConnection.java:20)
ojdbc.jar file is configured in the build path of the project. Is there a way to accomplish the result?
Double quotes.
You don't have to put double quotes in properties values.
so its:
DBCLASS=oracle.jdbc.driver.OracleDriver
and not
DBCLASS="oracle.jdbc.driver.OracleDriver"
The problem is shown in the expection message:
Exception in thread "main" java.lang.ClassNotFoundException: "oracle.jdbc.driver.OracleDriver"
If I write
Class.forName("HelloWorld");
I get the following exception message:
Exception in thread "main" java.lang.ClassNotFoundException: HelloWorld
Somehow your properties file contains not the class name, but the class name enclosed in quotes.
Strip of those quotes and your code will work.
See if there is an oracle.jdbc.driver.OracleDriver class in ojdbc.jar.
In simple ways, it is an import for the class with the fully qualified name oracle.jdbc.driver.OracleDriver and see is it report an error in your eclipse.

how to to connect and use JDBCUtil

hi
i want to use Class JDBCUtil in java language and eclips workspace and I have the below code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCUtil {
static final String CONN_STR = "jdbc:hsqldb:hsql://localhost/";
static {
try {
Class.forName("org.hsqldb.jdbcDriver");
} catch (ClassNotFoundException ex) {
System.err.println("Unable to load HSQL JDBC driver");
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(CONN_STR);
}
}
but when I run it, I get the below Exception:
Unable to load HSQL JDBC driver
Exception in thread "main" java.lang.NullPointerException
at domain.EnrollCtrl.getCurrentOfferings(EnrollCtrl.java:78)
at ui.UI.main(UI.java:28)
in addition there is UI and EnrollCtrl and another file in this project but the error is in this path.
how can i fix this error? should I do sth for connectin to jdbc:hsqldb:hsql://localhost/?
thank U
your String CONN_STR = "jdbc:hsqldb:hsql://localhost/"; should be
conn = DriverManager.getConnection(jdbc:hsqldb:hsql://localhost/xdb", "sa", "");
In some circumstances, you may have to use the following line to get the driver.
Class.forName("org.hsqldb.jdbcDriver").newInstance();
The chances are that you are missing the hsqldb.jar file from your classpath or some other environmental issue.
It is difficult to be certain as your question is incredibly specific to your code and environment.

Categories

Resources