How to fix mysql jdbc error: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test - jdbc

I have been looking for solution for my problem, but I did not get anywhere. I am using visual studio code to connect java(JDK-19) to MySQLv8.0 and I installed mysql-connector-j v8.0.31 (I am using windows)
I am trying to connect my database to java and I keep get this error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
This is my code:
import java.sql.*;
import java.util.Properties;
public class App {
public static void main(String[] args) throws Exception {
Connection dbConnection = null;
try {
String url = "jdbc:mysql://localhost:3306/test";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "test");
dbConnection = DriverManager.getConnection(url, info);
if (dbConnection != null) {
System.out.println("Successfully connected to MySQL database test");
}
} catch(SQLException e) {
System.out.println("An error occurd while connecting MySQL database");
e.printStackTrace();
}
}
}
I also added mysql-connector-j-8.0.31 jar file to referenced libraries.
Also added:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
to pom.xml

Related

Unable to connect hive in kerberos mode

Here is the code to connect to hive in kerberos mode
import java.sql.*;
import org.apache.hadoop.security.UserGroupInformation;
public class hive2 {
public static void main (String args[]) {
try {
org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();
conf.set("hadoop.security.authentication", "Kerberos");
UserGroupInformation.setConfiguration(conf);
UserGroupInformation.loginUserFromKeytab("hive/ambari2012.howard2012.local#HOWARD2012.LOCAL", "/etc/security/keytabs/hive.service.keytab");
Class.forName("org.apache.hive.jdbc.HiveDriver");
System.out.println("getting connection");
Connection con = DriverManager.getConnection("jdbc:hive2://ambari2012:10000/;principal=hive/ambari2012.howard2012.local#HOWARD2012.LOCAL");
System.out.println("got connection");
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
the issue is doesnt matter what keytab I pass it's always giving the below error -
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
java.io.IOException: Login failure for hive/ambari2012.howard2012.local#HOWARD2012.LOCAL from keytab /etc/security/keytabs/hive.service.keytab
at org.apache.hadoop.security.UserGroupInformation.loginUserFromKeytab(UserGroupInformation.java:921)
at hive.connect.java.hive.connect.java.App.main(App.java:21)
Caused by: javax.security.auth.login.LoginException: Unable to obtain password from user
I don't think it's even trying to check if the right keytab is given to it.
How should I ensure it's reading the correct keytab file and also if the keytab file is not present it should give unable to locate the keytab
Please let me know if I have to copy the keytab ,krb files in my local machine
I don't think you can connect to a kerberized HIVE this way.
Try using a JAAS file https://docs.oracle.com/javase/7/docs/technotes/guides/security/jgss/tutorials/LoginConfigFile.html
and add the 2 following properties to your JVM :
-Djavax.security.auth.useSubjectCredsOnly=False
-Djava.security.auth.login.config=jaas.conf
Sample file jaas.conf :
com.sun.security.jgss.krb5.initiate
{ com.sun.security.auth.module.Krb5LoginModule required
useKeyTab =true
useTicketCache =false
doNotPrompt =true
principal ="hive/ambari2012.howard2012.local#HOWARD2012.LOCAL"
keyTab ="/etc/security/keytabs/hive.service.keytab"
debug =false;
};
Client
{ com.sun.security.auth.module.Krb5LoginModule required
useKeyTab =true
useTicketCache =false
doNotPrompt =true
principal ="hive/ambari2012.howard2012.local#HOWARD2012.LOCAL"
keyTab ="/etc/security/keytabs/hive.service.keytab"
debug =false;
};
I was missing jar files so if you add all jar files it's fine, here is the complete code
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;
public class App {
private static Connection hiveConnection;
// get Hive Connection
public static void main(String [] args) throws IOException, SQLException {
String principal="principal";
String keytab="keytab";
Runtime rt = Runtime.getRuntime();
try{ Process p = rt.exec("kinit -k -t " + keytab + " " + principal);
p.waitFor(); }
catch(InterruptedException exception)
{
System.out.println("wait for threw an exception - it was interrupted");
exception.printStackTrace();
}
catch (IOException exception){
System.out.println("Exception in running kinit process") ;
exception.printStackTrace();
}
System.out.println("Preparing Hive connection1");
Configuration conf = new Configuration();
System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
conf.set("hadoop.security.authentication", "Kerberos");
UserGroupInformation.setConfiguration(conf);
UserGroupInformation.loginUserFromKeytab(principal, keytab);
// Hive Connection
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
if(hiveConnection == null) {
hiveConnection = DriverManager.getConnection("jdbc:hive2://host:10000/;principal=principal;auth=kerberos;kerberosAuthType=fromSubject");
// return hiveConnection;
System.out.println("Got Connection");
} else {
//return hiveConnection;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
// return null;
} catch (SQLException e) {
e.printStackTrace();
// return null;
}
}
}

Instrumentation: Casting org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper to oracle.jdbc.OracleConnection

I'm trying to instrument my jdbc connections. I know there are several similar questions about this topic.
I tried everything but couldn't find the propper way to solve my issue so far.
Also tried the answers to this question, with no result:
Apache Commons DBCP connection object problem, Thread: ClassCastException in org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper
I'm working with Tomcat 7 and Java 7. Here's where I define the oracle connection pool in my context.xml:
<Resource name="jdbc/myDS"
type="javax.sql.DataSource"
auth="Container"
maxActive="350"
maxIdle="50"
minIdle="10"
maxWait="10000"
username="user_own"
password="mypassw"
accessToUnderlyingConnectionAllowed="true"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:#192.168.110.173:1521/orcl" />
My instrumentation code:
private static void initInstrumentation(Connection con, final String usuario, final String modulo, final String accion) throws Exception {
if (Utils.getParameter("instrumentation.active").equals("1")) {
try {
OracleConnection oracleConnection = null;
//This is where I try to get the oracle connection, but no succeed
if (con != null) {
if (con instanceof OracleConnection) {//NEVER COME IN HERE
oracleConnection = (OracleConnection) con;
} else if (con.isWrapperFor(OracleConnection.class)) {//NEVER COME IN HERE
oracleConnection = con.unwrap(OracleConnection.class);
} else{
//NO ORACLECONNECTION NO isWrapperFor -> ALWAYS ENDS HERE!!!
//oracleConnection = (OracleConnection) ((DelegatingConnection) con).getDelegate();
oracleConnection = (OracleConnection) new DelegatingConnection(con).getInnermostDelegate();
}
}
if (oracleConnection != null) {
String[] metrics = new String[OracleConnection.END_TO_END_STATE_INDEX_MAX];
metrics[OracleConnection.END_TO_END_MODULE_INDEX] = modulo;
metrics[OracleConnection.END_TO_END_ACTION_INDEX] = "Inicio: " + accion;
metrics[OracleConnection.END_TO_END_CLIENTID_INDEX] = usuario;
oracleConnection.setEndToEndMetrics(metrics, (short) 0);
}
} catch (Exception e) {
throw new Exception("Error initInstrumentation " + e);
}
}
}
My open connection method:
private static Connection genericOpenConnection() throws Exception {
Connection con = null;
try {
DataSource dataSource = (DataSource) new InitialContext().lookup(Utils.cStrPlx(Utils.getParameter("dataSourceJndiName")));
con = dataSource.getConnection();
con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
} catch (Exception e) {
Error.escribeLog("Error : " + e.getMessage());
throw new SQLException(e.getMessage());
}
return con;
}
So after calling openConnection and initInstrumentation I'm getting the next exception trying to cast the connection to an oracle connection. Any ideas of how to do this? What am I getting wrong?
Thanks in advance.
java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper cannot be cast to oracle.jdbc.OracleConnection
I found my problem. I hope this can help anyone with the same issue.
The thing seems to be related to a conflict with the ojdbc driver libraries.
I have one driver in my tomcat, and another one declared in pom.xml via maven.
<!-- Driver oracle -->
<dependency>
<groupId>com.plexus</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0</version>
<scope>provided</scope>
</dependency>
Declaring this driver as provided fixed my problem, and the connection now is been retrieved as described below
if (con.isWrapperFor(OracleConnection.class)) {
oracleConnection = con.unwrap(OracleConnection.class);
}

Getting an error when try to connect to Oracle java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

i am trying connect to Oracle Database through following program. but throws an error
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver "
only SQL developer client is installed on my machine whereas Actual data base is store on Server. Please help on resolving the issue
package test;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class DBConnection {
public static void main(String[] argv) {
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
enter code here
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#hostname:5800:SID", "user","password");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
Add your Oracle JDBC Driver jar to the classpath
Can download the driver for your Oracle Database Version from here

Cannot connect to Derby DB on netbeans using JDBC

I am trying to manipulate an Apache Derby DB on NetBeans and I'm having a tough time connecting.
It seems very simple but it just wouldn't connect.
Please help. Thanks in advance!
import java.sql.*;
public class JDBCtutorial {
private static String tableName = "Diseases";
private static Connection conn = null;
private static Statement stmt = null;
public static void createConnection() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(ClassNotFoundException cnfe) {
System.out.println(cnfe);
}
try {
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/DBName", "user", "password");
} catch (Exception e) {
System.out.println("Cannot connect. . .");
}
}
public static void main(String[] args) {
createConnection();
}
}
You're using the driver for embedded use of Derby (org.apache.derby.jdbc.EmbeddedDriver), yet you try to connect over the network, in which case you should use the network driver, org.apache.derby.jdbc.ClientDriver.
All this is explained in detail in the Derby doc which is quite good.
Also, as probably getConnection is throwing an exception that might give some hints about the cause of the problem, try pinting the stacktrace, it should provide that info:
} catch (Exception e) {
System.out.println("Cannot connect:");
e.printStackTrace();
}
You Just need to add one library file in your project.
Download here
Eclipse : Right Click on project then > Build Path > Configure Build Path > Add External JAR (and select the file you downloaded) > Done
NetBeans : Right Click on project then > Properties > Libraries > ADD JAR/Folder
"and select the file you downloaded " > ok (Run)
Add Permanently : Add the file in c:/program files/java/JRE/lib/ folder

JDBC-ODBC connectivity

import java.sql.*;
public class QBreaker
{
public static void main (String[] args)
{
Connection conn = null;
String driver="sun.jdbc.odbc.JdbcOdbcDriver";
String url="jdbc:odbc:huss";
try
{
Class.forName(driver);
conn=DriverManager.getConnection(url,"sa","admin123");
System.out.println("Connection is created");
Statement db_statement=conn.createStatement();
ResultSet rs=db_statement.executeQuery("select * from Details");
while(rs.next())
{
System.out.print("ID: "+rs.getInt("Id"));
System.out.print("\tBalance: "+rs.getString("Bal"));
}
conn.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
This is my code to connect to the database.
i have created the odbc driver n followed all the required steps in dat.
but still while running the i got this exception:
Connection is created
java.sql.SQLException: [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'Details'.
Process completed.
There is no such table or view named Details exists. Please verify the database.
u create Data source ? , if u not created it can u go to control panel in windows then Administrative Tools then Data Sources (ODBC) .

Resources