Java JDBC connection to MySQL - java

I am trying to connect to mysql from java web application in eclipse.
Connection con = null;
try {
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/db_name","root" ,"");
if(!con.isClosed())
System.out.println("Successfully connected to " +
"MySQL server using TCP/IP...");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {
System.out.println(e.toString());
}
}
I am always getting the Exception: com.mysql.jdbc.Driver
I have downloaded this jar http://forums.mysql.com/read.php?39,218287,220327
import it to the "java build path/lib"
the mysql version is 5.1.3 under.
running:
mysql 5.1.3 (db is up and running queries form PHP)
windows XP
Java EE

you say you placed the JAR on the build path, is it in the runtime class path? you said "java EE", so i assume you are deploying this as a web app? in that case you need to put the JDBC JAR file into WEB-INF/lib of your web app.

You have to download the mysql jdbc connector und use it as lib. You can get it here:
http://www.mysql.com/downloads/connector/j/

Have u added it in your build configuration also, if the location is not in classpath then it wont work by mere keeping it in lib folder.
check your .classpath file

You can find a full documentation (Chapter 14) on how to connect to MySQL database through any web application (JBOSS, Glassfish etc...), if you download the MySQL JDBC driver.
After doing your configuration, you have to get the connection from your server by getting your server connection ressource.
Here is a sample code of how to get a connection ressource from a Glassfish server :
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
#Stateless
public class AppConnection {
private InitialContext context;
private DataSource source;
private Connection connection;
public AppConnection() {
this.initConnection();
}
private void initConnection() {
try {
context = new InitialContext();
source = (DataSource)context.lookup("jdbc/MySQLDataSource");
connection = source.getConnection();
} catch (SQLException ex) {
Logger.getLogger(AppConnection.class.getName()).log(Level.SEVERE, null, ex);
} catch (NamingException ex) {
Logger.getLogger(AppConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Connection getContextConnection() {
return connection;
}
public void closeContextConnection() throws SQLException {
if(connection != null) {
connection.close();
}
}
}
Note that this class is an EJB and "jdbc/MySQLDataSource" is the name of the connection configured on your server. It can be inject in other EJB to get your current connection and create other needed objects as Statements or Resultsets.

Related

java.sql.SQLException: No suitable driver found in Netbeans

I have this code in a class for the connection to the database.
package fullhouse;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FullhouseDB {
private static Connection databaseConnectie;
public static Connection getConnection() {
if(databaseConnectie == null){
String connectString = "jdbc:mysql://localhost:3306/fullhouse";
try {
databaseConnectie = DriverManager.getConnection(connectString, "root", "2002112735");
} catch (SQLException ex) {
Logger.getLogger(FullhouseDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
return databaseConnectie;
}
And I get this error:
dec 29, 2014 5:05:49 PM fullhouse.FullhouseDB getConnection
SEVERE: null
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/fullhouse
I've checked the username and password, the connection of database services, and all is correct.
You need to load the driver class using:
Class.forName("com.mysql.jdbc.Driver");
And then define connect string url.
String connectString = "jdbc:mysql://localhost:3306/fullhouse";
First you take mysql driver file from the url below url
http://projectshub.in/softwares/mysql/mysql-connector-java-5.0.8-bin.jar
than add this driver file to your project lib folder.

Unable to connect to SSAS using olap4j on Linux

I wish to connect to SSAS 2012 using Java and have tried olap4j driver for the same.
I am working on Linux (Ubuntu 14.04) platform.
I have read that Olap4j works for Windows but will it work on Linux ?
I have written some Java code which gives runtime error. This error is because the Linux machine is unable to connect to SSAS.
I have set http access and IIS server and using msmdpump.dll to connect.
Below is the Java code and the error.:
CODE
package ssas;
import java.sql.Connection;
//import java.lang.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.olap4j.Cell;
import org.olap4j.CellSet;
import org.olap4j.OlapConnection;
import org.olap4j.OlapException;
import org.olap4j.OlapStatement;
import org.olap4j.OlapWrapper;
import org.olap4j.Position;
import org.olap4j.metadata.Member;
public class connexionSSAS
{
public static void main(String[] args) throws ClassNotFoundException,
OlapException {
Class.forName("org.olap4j.driver.xmla.XmlaOlap4jDriver");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:xmla:Server=http://01XXXXXXXX/olap/msmdpump.dll;" +
"Catalog=sample_Cube");
} catch (SQLException e) {
e.printStackTrace();
}
if (null == connection) {
System.out.println("Cnul");
}
OlapWrapper wrapper = (OlapWrapper) connection;
OlapConnection olapConnection = null;
try {
olapConnection = wrapper.unwrap(OlapConnection.class);
} catch (SQLException e) {
e.printStackTrace();
}
olapConnection.setCatalog("sample_Cube");
OlapStatement statement = null;
CellSet cellSet = null;
System.out.println(olapConnection.getCatalog());
try {
statement = (OlapStatement) olapConnection.createStatement();
CellSet=statement.executeOlapQuery(
"Summarize(FactDiagnosis,FactDiagnosis[ImportDateKey])");
args}
catch(SQLException e) {
e.printStackTrace();
}
}
}
ERROR
Exception in thread "main" java.lang.RuntimeException: org.olap4j.OlapException: This connection encountered an exception while executing a query.
at org.olap4j.driver.xmla.DeferredNamedListImpl.getList(DeferredNamedListImpl.java:96)
at org.olap4j.driver.xmla.DeferredNamedListImpl.size(DeferredNamedListImpl.java:116)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.getOlapDatabase(XmlaOlap4jConnection.java:451)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.getOlapCatalogs(XmlaOlap4jConnection.java:527)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.setCatalog(XmlaOlap4jConnection.java:483)
at ssas.connexionSSAS.main(connexionSSAS.java:49)
Caused by: org.olap4j.OlapException: This connection encountered an exception while executing a query.
at org.olap4j.driver.xmla.XmlaHelper.createException(XmlaHelper.java:43)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.executeMetadataRequest(XmlaOlap4jConnection.java:878)
at org.olap4j.driver.xmla.XmlaOlap4jDatabaseMetaData.getMetadata(XmlaOlap4jDatabaseMetaData.java:137)
at org.olap4j.driver.xmla.XmlaOlap4jDatabaseMetaData.getMetadata(XmlaOlap4jDatabaseMetaData.java:67)
at org.olap4j.driver.xmla.XmlaOlap4jDatabaseMetaData.getDatabaseProperties(XmlaOlap4jDatabaseMetaData.java:1044)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.makeConnectionPropertyList(XmlaOlap4jConnection.java:324)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.generateRequest(XmlaOlap4jConnection.java:1037)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.populateList(XmlaOlap4jConnection.java:849)
at org.olap4j.driver.xmla.DeferredNamedListImpl.populateList(DeferredNamedListImpl.java:136)
at org.olap4j.driver.xmla.DeferredNamedListImpl.getList(DeferredNamedListImpl.java:90)
... 5 more
This code will run if I comment the statements containing 'OlapConnection'.
Any help would be appreciated.

In my application in java database connection code is not working

In this code class.forname it show error that class not found
so help me with this code because my is a local database application
I am using sqlite database.
package appview;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Databaseconnection {
Connection connection = null;
public static Connection connection2()
{
try
{
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Jainam\\Java Application\\JPH\\src\\database\\jph_db.sqlite");
return connection;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
You have to declare the url this way: jdbc:sqlite:/DRIVE:/dirA/dirB/dbfile
DriverManager.getConnection("jdbc:sqlite:/C:/Users/Jainam/Java Application/JPH/src/database/jph_db.sqlite");
See Here for more informations
ClassNotFoundException means Java is not able to find the org.sqlite.JDBC class. You need to Download sqlite-jdbc-3.6.20.1.jar and put it in your class-path before running it.
here check database connectivity.
class not found ? then go for DDMS->FILE EXP-> SDCARD -> INSERT UR SQLITE.DB file.It will run proper.

Connect to MySQL using JDBC driver through a proxy [duplicate]

This question already has an answer here:
MySQL Connect via proxy in Java
(1 answer)
Closed 2 years ago.
In Java, I would like to make a connection to a MySQL server which is on the web from a client computer that is behind a http proxy. I have read few solutions some say http tunnelling might work and some suggest a very old link from oracle which is not available anymore. So the question is:
How can we connect to a MySQL server from a computer which is behind a http proxy?
You can try the following code and see if it works. It worked for me over TCP
package indika.jdbc.connectivity;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class ConnectOverProxy {
public static void main(String[] args) {
new ConnectOverProxy();
}
public ConnectOverProxy() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
Properties info = new Properties();
//info.put("proxy_type", "4"); // SSL Tunneling
info.put("proxy_host", "[proxy host]");
info.put("proxy_port", "[proxy port]");
info.put("proxy_user", "[proxy user]");
info.put("proxy_password", "[proxy password]");
info.put("user", "[db user]");
info.put("password", "[db pass word]");
conn = DriverManager.getConnection("jdbc:mysql://[db host]/",info);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select NOW()");
rs.next();
System.out.println("Data- " + rs.getString(1));
rs.close();
stmt.close();
conn.close();
} catch (SQLException er) {
er.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Also look at "http://www.idssoftware.com/jdbchttps.html", However I have not used this personally.

Database Connection via WebLogic

So I have a MySQL database, and I have a datasource on a local instance of WebLogic which is connected to that database. I am trying to write some client code which will simply connect and query. I am having issues with obtaining a connection from the datasource. Here's my code thus far. I am running WebLogic 12c.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ConnectionTest {
public static void main(String... args) {
ConnectionTest tCon = new ConnectionTest();
tCon.TestConnection();
}
public void TestConnection() {
Context ctx = null;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("java.naming.factory.initial",
"weblogic.jndi.WLInitialContextFactory");
props.put("java.naming.provider.url", "t3://localhost:7001");
props.put("java.naming.security.principal", "weblogic");
props.put("java.naming.security.credentials", "welcome1");
ctx = new InitialContext(props);
DataSource ds = (DataSource) ctx.lookup("RegexDB");
System.out.println(ds);
DAO dao = new DAO();
conn = ds.getConnection();
stmt = conn.createStatement();
stmt.execute("select * from regular_ex");
rs = stmt.getResultSet();
ArrayList<HashMap<String, Object>> results = dao
.resultSetToArrayList(rs);
dao.printArrayList(results);
stmt.close();
conn.close();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
This fails at ds.getConnection() with the following exception:
java.lang.ClassCastException: weblogic.jdbc.common.internal.ConnectionEnv cannot be cast to java.io.Serializable
at weblogic.iiop.IIOPOutputStream.writeObject(IIOPOutputStream.java:2285)
at weblogic.utils.io.ObjectStreamClass.writeFields(ObjectStreamClass.java:414)
at weblogic.corba.utils.ValueHandlerImpl.writeValueData(ValueHandlerImpl.java:235)
at weblogic.corba.utils.ValueHandlerImpl.writeValueData(ValueHandlerImpl.java:225)
at weblogic.corba.utils.ValueHandlerImpl.writeValue(ValueHandlerImpl.java:182)
at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:1983)
at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:2021)
at weblogic.iiop.IIOPOutputStream.writeObject(IIOPOutputStream.java:2285)
at weblogic.jdbc.common.internal.RmiDataSource_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:695)
at weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:230)
at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:520)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:516)
at weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
I have wlclient.jar, wlsafclient.jar, and weblogic.jar in my buildpath. I have tried all sorts of combinations of adding/removing these jars, but I still get the same error regardless of what I do. Any help would be greatly appreciated.
After doing some research, I am deleting my old answer and starting over.
There is a large table of client types in the Oracle Doc for WebLogic Standalone Clients. For each type of client, listed, the table shows the required jar files. For certain types of clients, you need to build an additional jar (wlfullclient.jar) and include that.
Hope this helps.
I have also face this problem and I tried to add "wlfullclient.jar" to my directory to fix it out but I didn't find this jar file in weblogic installation folder.
But at the last I have set all required jar files form weblogic by using setDomainEnv.cmd and it works fine. Here we don't have to care about which jar files required or not it'll simply set classpath for all required jar file for your program.
I am using Weblogic 11g.
In Weblogic 12c, copy the weblogic.jar file to some other directory. Rename the file to weblogic-classes.jar and then build the jar file using wljarbuilder.
Add the newly created wlfullclient.jar file to your Class Path in eclipse.
Build wlfullclient.jar and add just this jar to the build path.
It solved the problem for me.
By the way weblogic.jar from Weblogic 12 is missing some classes as compared to weblogic.jar from Weblogic 10.3

Categories