How to connect data base using jndi datasource in weblogic. i am using following code but it is giving null value for connection
Context ctx = null;
Hashtable evn = new Hashtable();
evn.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
evn.put(Context.PROVIDER_URL,"t3://localhost:7001");
Connection conn = null;
try {
ctx = new InitialContext(evn);
javax.sql.DataSource ds
= (javax.sql.DataSource) ctx.lookup ("mydatasource");
conn = ds.getConnection();
}catch (Exception e) {
System.out.println();
// TODO: handle exception
}
Append this to clarify more about exception reason
catch(Exception sqlExp)
{
throw new SQLException("getConnection :: Exception"+sqlExp);
}
post the exception as suggested by Stano
on weblogic console test the connection
http://docs.oracle.com/cd/E23943_01/web.1111/e13737/jdbc_datasources.htm#CHDIIFHH
did you target the datasource to weblogic server where the application works?
//try this code:
Connection con = null;
DataSource datasource = null;
Context initialContext = new InitialContext();
// "jdbc/MyDBname" >> is a JNDI Name of DataSource on weblogic
datasource = (DataSource) initialContext.lookup("jdbc/MyDBname");
con = datasource.getConnection();
Related
I'm new to Java and I want to connect with MySQL local server, but it's throwing an exception error. How can I fix the code?
Connection information:
Lport:3306
database name= siba_1
table name= test_1
Code:
package java_recap;
import java.sql.*;
public class Java_recap {
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mqsql://localhost:3306/siba_1","root","");
Statement stn=con.createStatement();
ResultSet rs=stn.executeQuery("select * from test_1");
while(rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
}
catch(Exception e){
System.out.println("e");
}
}
}
DriverManager is a old way of doing things. if you still want to use DriverManger then:
Need mysql dependency add jar on classpath or use maven like below :
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
Now Let's see how we can connect to our database and execute a simple select-all through a try-with-multiple-resources:
String sql = "select * from test_1";
String connectionUrl = "jdbc:mysql://localhost:3306/siba_1?
serverTimezone=UTC";
try (Connection conn = DriverManager.getConnection(connectionUrl,
"root", "");
PreparedStatement ps =
conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString(1)+" "+rs.getString(2));
// do something with the extracted data...
}
} catch (SQLException e) {
// handle the exception
}
Other way : The better way is to get a DataSource either by looking one up that your app server container already configured for you:
Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/siba_1");
or instantiating and configuring one from your database driver directly:
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("root");
dataSource.setPassword("");
dataSource.setServerName("localhost");
and then get connections from it, same as above:
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from test_1");
...
rs.close();
stmt.close();
conn.close();
I am trying to connect to a DB2 database using SSL on IBM Bluemix.
When I first tried to connect without SSL, it doesn't work. After reading the documentation, I have realized that it connects to the database with SSL enabled.
I tried using the following code to get it connect to the database:
public boolean connect() {
try {
String url = "jdbc:db2://" + serverName + ":" + port + "/" + dbName+
":securityMechanism=9";
connection = DriverManager.getConnection(url, userName, passWord);
st = connection.createStatement();
return true;
} catch (Exception e) {
System.err.println(e.getMessage());
}
return false;
}
Still I am not too sure on how to use the SSL certificate provided with the code above.
I tried searching for examples but most of the explanations are either unclear or used for another database system.
If you are using Liberty, a datasource is generated for you, and you can look it up using jndi.
#Resource(lookup = "jdbc/mydb")
private DataSource myDataSource;
Connection c = myDataSource.getConnection();
"mydb" is the name of the SQLDB service
https://developer.ibm.com/bluemix/2014/02/07/java-db2-10-minutes/
According to the SQLDB documentation, If you use the latest com.ibm.db2.jcc.DB2Driver with the JDBC connection, the current SSL certificate is bundled with the driver and does not need manually installing.
The following snippet shows you how to use the connection details available from VCAP_SERVICES to connect to SQLDB over SSL.
public class SSLTEST {
/**
* #param args
*/
public static void main(String[] args) {
String ServerName = "hostname or IP address";
int PortNumber = 50001;
String DatabaseName = "SQLDB";
String user = "your_user_id_from_VCAP_SERVICES";
String userPassword = "your_password_from_VCAP_SERVICES";
java.util.Properties properties = new java.util.Properties();
properties.put("user", "user ID that has access to SQLDB");
properties.put("password", "password for the user ID that has access to SQLDB");
properties.put("sslConnection", "true");
String url = "jdbc:db2://" + ServerName + ":"+ PortNumber + "/" +
DatabaseName + ":" + traceFileLocation + ";";
java.sql.Connection con = null;
try
{
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
}
catch ( Exception e )
{
System.out.println("Error: failed to load Db2 jcc driver.");
}
try
{
System.out.println("url: " + url);
con = java.sql.DriverManager.getConnection(url, properties);
if (con != null) {
System.out.println("Success");
} else {
System.out.println("Failed to make the connection");
}
con.close();
}
catch (Exception e)
{
if (con != null) {
try {
con.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
e.printStackTrace();
}
}
finally i use datasource to connect to the database.
Context ic = new InitialContext();
DataSource db = (DataSource)context.lookup("jdbc/MyDatabase");
I have JNDI config for all possible database connectivity in my application. Meanwhile I am using JUNIT to test my applications. I find successful connection form my webservices class invocation but error throws while calling it through junit test class.
My JNDI setting is
public static Connection getConnectionPool() {
Connection conn = null;
System.out.println("Creating connection pool.");
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup(getJNDIName());
conn = ds.getConnection();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (NamingException e) {
e.printStackTrace();
}
return conn;
}
private static String getJNDIName()
{
if(!readJNDI)
{
try{
Properties prop = new Properties();
prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
JNDIName = prop.getProperty("jndi.name");
System.out.println("JNDIName : "+JNDIName);
readJNDI = true;
}catch(Exception ex){
ex.printStackTrace();
}
}
return JNDIName;
}
Below mentioned is the error.
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
How do I resolve it.?
Thanks in advance.
You should use a local datasource.
Just pull out the DataSource/TransactionManager definition into a separate XML file, and use that instead of the JNDI one during testing.
You can still use all the rest of your configuration.
I'm getting "While trying to lookup 'jdbc.LogDB' didn't find subcontext 'jdbc'. Resolved ''" error when i try to get connection from the Weblogic. I created and tested the datasource and it's working. Also created the target servers. Datasource name is "jdbc/LogDb". Below is the test code i wrote.
public class TestUtils {
private static final Logger logger = LoggerFactory.getLogger(TestUtils.class.getName());
public DataSource ds = null;
public String testConnectionPool() throws SQLException {
Context ctx = null;
Hashtable ht = new Hashtable();
Connection conn;
String result = "";
ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3://localhost:7001");
ht.put(Context.SECURITY_PRINCIPAL, "weblogic");
ht.put(Context.SECURITY_CREDENTIALS, "weblogic");
try {
ctx = new InitialContext(ht);
ds = (DataSource) ctx.lookup("jdbc/LogDB");
logger.debug("Weblogic Connection Pool Created");
conn = ds.getConnection();
Statement stmt = conn.createStatement();
stmt.execute("some sql");
ResultSet rs = stmt.getResultSet();
if(rs.next()){
result = result + rs.getString(1);
}
stmt.close();
conn.close();
} catch (NamingException e) {
logger.error("Naming Exception occured at connect: " + e.getMessage());
} catch (Exception e){
logger.error("Exception occured at connect: "+ e.getMessage());
} finally {
try {
if (ctx != null) {
ctx.close();
}
}
catch (Exception e) {
logger.error("Ctx Error");
}
}
return result;
}
}
I tried the following names
"java:jdbc/LogDb"
"java:comp/env" variations etc.
Thanks for the kind answers
I have a Servlet which initializes its DataSource in the Servlets init method (because it is accessed there the first time). When the servlet is getting loaded I get the following exception message
Cannot create JDBC driver of class '' for connect URL 'null'
But when the first request is processed the jndi lookup works fine and the DataSource is initialized properly.
Here is my DataSource class:
public class PostgresDataSource{
private static DataSource dataSource;
static {
try {
dataSource = (DataSource) new InitialContext().lookup("java:/comp/env/jdbc/somedb");
} catch (NamingException e) {
Log.logger.fatal("Failed to initialize DB!");
Log.logger.error(e.getMessage());
e.printStackTrace();
}
}
public static Connection checkOut(){
if ( dataSource != null )
{
try {
return dataSource.getConnection();
} catch (SQLException e) {
Log.logger.error("Failed to establish DB connection!");
Log.logger.error(e.getMessage());
e.printStackTrace();
return null;
}
}
else
{
Log.logger.error("Failed to check out DB-Connection: Postgres DataSource not initialized!");
return null;
}
}
public static void checkIn( Connection dbcon){
if ( dataSource != null )
{
try {
dbcon.close();
} catch (SQLException e) {
Log.logger.error("Failed to close DB connection!");
e.printStackTrace();
}
}
else
{
Log.logger.error("Cannot check in DB-Connection: Postgres DataSource not initialized!");
}
}
}
Anyone encountered the same problem? What's the reason for this and how to solve it?
Instead of using
dataSource = (DataSource) new InitialContext().lookup("java:/comp/env/jdbc/somedb");
Please use the following, this may solve the problem
InitialContext context = new InitialContext();
Context envCtx = (Context) context.lookup("java:comp/env");
dataSource = (DataSource) envCtx.lookup("jdbc/somedb");