import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
//This class is for testing connection with mysql database
class JDBCTest {
// path to database is stored in string url
private static final String url = "jdbc:mysql://localhost";
// username is stored in string root
private static final String user = "root"; //username
// password is stored in string password
private static final String password = "swapnil";//password
public static void main(String args[]) {
try {
//i have stored driver in c:\javap\
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url, user, password);
System.out.println("Success");
} catch (Exception e) {
System.out.println("hi");
e.printStackTrace();
}
}
}
whenever I try to run this program I get the exception
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
I am using mysql database my operating system is windows 7 64 bit. I have included the mysql-connector-java-5.1.22-bin in jdk/jre/lib/ext I have also set up the CLASSPATH Environment variable but nothing work me out
First of all, you should not put anything under the JDK's jre/lib/ext directory.
Instead, use the -cp option when launching your application, and make sure to have the jar of the driver (and not the bin directory) in the classpath:
java -cp mysql-xx.jar;... com.foo.bar.JDBCTest
The URL is incomplete use:
private static final String url = "jdbc:mysql://localhost:3306/databasename";
also as #JB Nizet mentioned do not put jars in jdk's lib.
Related
I have developed liquibase maven project which updates the Oracle RDS Database schema through changelog.sql file.
It runs successfully in the local environment but when I try to deploy this on bamboo in the Development environment SSL connection gets failed with the below message.
[Error] liquibase.exeception.DatabaseException: liquibase: Connection could not be created to jdbc:oracle:thin#(DESCRIPTION=(ADDRESS=(PROTOCOL=TCPS)(HOST=xyz.us-east1.rds.amazon.com)(PORT=2145))(CONNECT_DATA=(SID=OYKXXX1X)))?useSSL=true&requireSSL=true&verifyServerCertificate=true with driver oracle.jdbc.driver.OracleDriver. IO Error: IO Error General SSLEngine problem, connect lapse 20 ms., Authentication lapse 0ms.
Below is my liquibase.properties shell file
cat <<eof > ${bamboo_result_artifactId}-{bamboo_result_versin}/src/main/resources/liquibase.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin#(DESCRIPTION=(ADDRESS=(PROTOCOL=TCPS)(HOST=xyz.us-east1.rds.amazon.com)(PORT=2145))(CONNECT_DATA=(SID=OYKXXX1X)))?useSSL=true&requireSSL=true&verifyServerCertificate=true
username=xyz1234
password=ABC_22323_XYZ
changeLogFile=src/main/resources/db/chagelog/db.changelog-master.yml
eof
I have hardcoded the username and password to test the connection of liquibase with the Oracle RDS database.
Requested to please help me in this.
The issue looks in your URL. Kindly check if you have entered the correct url in the liquibase.properties file. Usage should look like this:
JDBC:oracle:thin:#{host}[:{port}]/{database}
In your case, your URL may look like this:
jdbc:oracle:thin#xyz.us-east1.rds.amazon.com:2145/OYKXXX1X?useSSL=true&requireSSL=true&verifyServerCertificate=true
Finally, I need to change the structure of code from Maven liquibase to Spring-boot liquibase project and I was able to establish liquibase to RDS SSL connection successfully.
package com.lmig.grs.springliquibase;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Objects;
#Configuration
public class SSLConfiguration {
public static final String JAVAX_NET_SSL_TRUST_STORE = "javax.net.ssl.trustStore";
public static final String JAVAX_NET_SSL_TRUST_STORE_PASSWORD = "javax.net.ssl.trustStorePassword";
public static final String JAVAX_NET_SSL_TRUST_STORE_TYPE = "javax.net.ssl.trustStoreType";
public static final String JAVAX_NET_SSL_KEY_STORE = "javax.net.ssl.keyStore";
public static final String JAVAX_NET_SSL_KEY_STORE_PASSWORD = "javax.net.ssl.keyStorePassword";
public static final String JAVAX_NET_SSL_KEY_STORE_TYPE = "javax.net.ssl.keyStoreType";
public static final String ORACLE_NET_SSL_SERVER_DN_MATCH = "oracle.net.ssl_server_dn_match";
public static final String JKS = "JKS";
public static final String PASSWORD = "changeit";
public static final String KS_FILE_NAME = "clientkeystore";
#PostConstruct
private void configureSSL() throws URISyntaxException {
URL clientKeystoreUrl = SSLConfiguration.class.getClassLoader().getResource(KS_FILE_NAME);
// LOGGER.info(String.format("Classloader.clientkeystore [%s]", clientKeystoreUrl));
final File tempKeystore = new File((Objects.requireNonNull(clientKeystoreUrl)).getFile());
System.setProperty(JAVAX_NET_SSL_TRUST_STORE, tempKeystore.getAbsolutePath());
System.setProperty(JAVAX_NET_SSL_TRUST_STORE_PASSWORD, PASSWORD);
System.setProperty(JAVAX_NET_SSL_TRUST_STORE_TYPE, JKS);
System.setProperty(JAVAX_NET_SSL_KEY_STORE, tempKeystore.getAbsolutePath());
System.setProperty(JAVAX_NET_SSL_KEY_STORE_PASSWORD, PASSWORD);
System.setProperty(JAVAX_NET_SSL_KEY_STORE_TYPE, JKS);
System.setProperty(ORACLE_NET_SSL_SERVER_DN_MATCH, "true");
}
}
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.
This is probably a simple fix or issue, but I am new to java and not sure how to do it. I have a web service that I am creating and a bunch of java files that I have with different data inputs. I want to be able to use the variables already defined in my other java files in my new file. Below you will see my code. For example on the first part of code, SponsorOrganizationalIdentifier is a column name in my MySQL database, along with a name already declared in other java files. How do I use the different variables that I have already declared in my other webserivce .java files?
Thanks for all your help!
package org.example.www.newwsdlfile3;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class JavaMYSQL {
public static void main(String[] args) throws Exception {
getConnection();
String sql = "INSERT INTO tableName values(':SponsorOrganiationalIdentifier', ':AgencyPersonGUID',':PersonID')";
String mySponsorID ="";
mySponsorID = "local"
sql = sql.replace(":SponsorOrganizationIdentifier", );
System.out.println(sql);
String AgencyGUID =""
AgencyGUID =
sql = sql.replace(:AgencyPersonGUID, )
System.out.println(sql)
String PersonIdent
PersonIdent =
sql = sql.replace(:PersonID,)
System.out.println(sql)
}
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/exchangeinformation";
String username = "root";
String password = "admin";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch (Exception e) {System.out.println(e);}
return null;
}
}
If you have constant data like column names, consider creating a class then defining them as static final class data.
For example:
class TestClass {
public static final String MY_COLUMN_NAME = "COLUMN_NAME";
}
Then you can access this variable in another class using TestClass.MY_COLUMN_NAME .
If the data is not final (constant) then this becomes a more complicated problem which is solved by writing a correctly structured program.
Could someone explain to me where I'm going wrong with the following code:
package newdbtet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewDBTet {
public static void main(String[] args) throws InstantiationException, SQLException, IllegalAccessException {
try {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "evidence_db";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
System.out.println("Connected to the database");
conn.close();
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewDBTet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Exception error:
Jul 16, 2012 2:59:24 PM newdbtet.NewDBTet main
SEVERE: null
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Does this mean that I haven't installed the driver / library correctly? Sorry - not the best with Java.
download the MySQL Driver for Eclipse/Java then you should get a .jar driver. then right click on your class and go to build path. finally add the external library to your project, that should solve your problem.
Add the JDBC driver .jar into the class path with a -cp command, i.e. - java -cp MysqlDriver.jar; MyProgram or add the .jar into the build path in your IDE.
I have created the web service and in that i am coonecting the database and access the information form that but couldn't successful.
/
**
*
*/
package com.xxxxx.www.testprocess;
import javax.jws.*;
import java.sql.*;
import java.util.*;
/**
* #author Suryasol6
*
*/
#WebService(name="TestProcess",targetNamespace ="http://www.example.org/TestProcess")
public class TestProcess {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
private static final String CONNECTION_URL = "jdbc:mysql://localhost:3306/java_test?user=root&;password=";
#WebMethod(action="http://www.example.org/TestProcess/TestLogin")
#WebResult(name="TestLoginresponse")
public String TestLogin(#WebParam(name="name")
String name,#WebParam(name="password")
String password)
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch(Exception e)
{
return "fail here";
}
return "pass";
}
}
I can publish the web service but when i try to connect the web service with parametes, it fails to load the jdbc driver.
But when i try to run this file as seperate this worked.
Can anybody help me??
Do you have the MySQL driver jar in the JBoss server lib directory? It should go in:
<JBoss_home>/server/default/lib
When you run it manually you may be specifying the classpath to include the jar, but JBoss needs it there.