JDBC driver error and cannot connect to MySQL [duplicate] - java

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
What is a classpath and how do I set it?
(10 answers)
Closed 5 months ago.
I keep getting the error messages when I run my code attempting to connect to a MySQL server
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:375)
This is my code. I've made sure to add connector/J to the classpath and still no change.
import java.sql.*;
public class App {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/vehicle", "root", "root"); // For MySQL only
vehicle focus = new vehicle("Ford", "Focus", 200, 2004, 3000);
System.out.println(focus.getMake());
}
}

First of all, loading the JDBC driver using Class.forName is not necessary since JDBC 4.0 which was made available in 2006 (the driver registers its implementation as service provider and will be loaded by the ServiceLoader).
Just remove this line and it should work. If you need the class name, its a good idea to consult the documentation of Connector/J. Take care to read the docs for the correct driver version because the class name changed (currently it's com.mysql.cj.jdbc.Driver).
Update
As Mark Rotteveel pointed out, Class.forName("com.mysql.jdbc.Driver") will not lead to a ClassNotFoundException when used with newer version of Connector/J. At least the newest driver produces a warning:
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new
driver class is `com.mysql.cj.jdbc.Driver'. The driver is
automatically registered via the SPI and manual loading of the driver
class is generally unnecessary.
Knowing this, removing Class.forName won't help since the exception simply means, that the driver is not on the class path.

Related

need to access hsqldb static method but get java.sql.SQLSyntaxErrorException: user lacks privilege or object not found

I'm trying to access the deserialize static method within the hsqldb (2.5.1) InOutUtil class. When I run it, java -cp hsqldb.jar:. testcode
I get:
java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: org.hsqldb.lib.InOutUtil.deserialize
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.execute(Unknown Source)
at testcode.main(testcode.java:58)
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: org.hsqldb.lib.InOutUtil.deserialize
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.result.Result.getException(Unknown Source)
... 4 more
Code:
...
connection = DriverManager.getConnection(dburl, "sa", "");
statement = connection.createStatement();
statement.execute("call \"java.lang.System.setProperty\"('org.apache.commons.collections.enableUnsafeSerialization','true')");
statement.execute("call \"org.hsqldb.lib.InOutUtil.deserialize\"('" + my_object +"');");
...
This is the offending line that throws the exception:
statement.execute("call \"org.hsqldb.lib.InOutUtil.deserialize\"('" + my_object +"');");
What I'm trying to do is reproduce this exploit, https://github.com/Critical-Start/Team-Ares/tree/master/CVE-2020-5902, on a local instance of hsqldb.
Not sure what I'm doing wrong. Thanks!
The exploit you linked to refers to HSQLDB version 1.8.0 which has been obsolete since the release of version 2.0 in 2010. However, aspects of the the security framework remain the same up to the latest version of HyperSQL.
A database user with even the DBA credentials cannot execute any arbitrary static method that happens to be in the classpath of the database server. A sysadmin who starts the database server can issue an allow-list of the specific static methods that are allowed to run as callable procedures, using the hsqldb.method_class_names Java System property with the list. See: http://hsqldb.org/doc/2.0/guide/sqlroutines-chapt.html#src_jrt_access_control
The listed safe static methods can then be turned into SQL callable procedures only by DBA credentials. EXECUTE privileges on the procedures are granted by the DBA.
Versions 2.x of HyperSQL generally improve upon the older security framework, for example allows secure password hash algorithms, password check and retention policies, including external authentication via LDAP and other frameworks.
You may succeed if you "try harder" and find the way HSQLDB expects parameter type definitions.
With HSQLDB 2.7.1 the maintainer's answer is enforced by either the absence or the presence of the server's system property (in addition to the connecting user's privilege needed to execute procedures). The server requires an explicit permission in its own Java properties such as -Dhsqldb.method_class_names="org.hsqldb.lib.StringConverter.*". (Using just the class name did not enable its static methods for me).
$ java -jar ~/hsqldb-svn-trunk/lib/sqltool.jar --inlineRc="url=jdbc:hsqldb:hsql://localhost/test,user=sa,password=" --sql="CALL \"org.hsqldb.lib.StringConverter.getUTFSize\"('java.class.path');"
15
With older HSQLDBs (or with a dangerously wide class name permission in 2.7.1), the only hurdle is to correctly declare the Java method's parameter types. I already figured that byte corresponds to TINYINT. I just need to learn the array mapping.
$ nl=$'\n'; java -cp ~/hsqldb-svn-trunk/lib/sqltool.jar org.hsqldb.cmdline.SqlTool --inlineRc="url=jdbc:hsqldb:hsql://localhost/test,user=sa,password=" --sql="CREATE FUNCTION TEST (BINARY) RETURNS BINARY NO SQL LANGUAGE JAVA EXTERNAL NAME 'CLASSPATH:org.hsqldb.lib.InOutUtil.deserialize';${nl}.;"
Feb 14, 2023 2:29:58 PM org.hsqldb.cmdline.SqlTool objectMain
SEVERE: SQL Error at '--sql' line 2:
"CREATE FUNCTION TEST (BINARY) RETURNS BINARY NO SQL LANGUAGE JAVA EXTERNAL NAME 'CLASSPATH:org.hsqldb.lib.InOutUtil.deserialize';"
user lacks privilege or object not found: org.hsqldb.lib.InOutUtil
org.hsqldb.cmdline.SqlTool$SqlToolException

Error in connecting to AS400 DB2 server JDBC

I am trying to connect to the AS400 DB2 database using the JDBC in a java program but I am unable to connect as it is giving a SQLException stating No suitable driver found for ​jdbc:as400://192.168.1.11
Whereas I added No suitable driver found for ​jdbc:as400://192.168.1.11
I added the following libraries to my project: db2jcc_licence_cu.jar, db2jcc4.jar, jt400-6.4.jar.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
public class ReadAllTables {
public static void main(String args[]) throws Exception {
//Class.forName ("com.ibm.as400.access.AS400JDBCDriver");
DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver());
// Enable logging
// DriverManager.setLogStream(System.err);
System.out.println("Getting Connection");
Connection c = DriverManager.getConnection ("​jdbc:as400://ipaddress","username","password");
DatabaseMetaData md = c.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
System.out.println(rs.getString(3));
}
}
}
This is what the error I am getting:
Getting Connection
Exception in thread "main" java.sql.SQLException: No suitable driver found for ​jdbc:as400://192.168.1.11
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.test.ReadAllTables.main(ReadAllTables.java:18)
Thanks in advance
You must have jt400.jar in your classpath for the AS/400 JDBC driver to work.
Version 7.10 is in Maven or download the latest from https://sourceforge.net/projects/jt400/ or copy it from IFS. The native CC driver is only used when running locally on the AS/400.
Given your current list of jars it sounds like your CLASSPATH variable is incorrect (or if you use a runnable jar, your Class-Path line in the manifest file is wrong). If you launch with RUNJVA the mechanism is different.

JdbcOdbc Driver Failed to Load [duplicate]

This question already has answers here:
Exception on loading JDBC-ODBC driver
(2 answers)
Closed 7 years ago.
public class DBtest
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (Exception e)
{
System.out.println("JDBC-ODBC driver failed to load.");
return;
}
}
}
Showing Exception Message
"JDBC ODBC Driver failed to load"
I have 2 questions
1-Where This JdbcOdbcDriver can be foud for MS ACCESS ?
2-If MS access Drier option in Administrative tool -> ODBC(64-bit)-> System DSN->Select Driver indicate the JDBC ODBC driver for connectivity then why it is not connecting
You didn't specify the java version you're using. Supposing you're using the latest JDK, JdbcOdbc driver is no longer available.

Unable to connect to Oracle 11g using jdbc

I'm trying to connect to Oracle 11g using jdbc as below but its giving me error. I had downloaded and kept jars in eclipse (ojdbc6dms.jar and ojdbc6dms_g.jar), but still its giving error
public static Connection getDatabaseConnection() throws SQLException,
InstantiationException, IllegalAccessException,
ClassNotFoundException {
Connection con = null;
// initialising drive
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
// load driver
con = DriverManager.getConnection(
"jdbc:oracle:thin:#10.16.52.79:1521:TST", "rep",
"Appe");
String dbName = con.getMetaData().getDatabaseProductName();
System.out.println(" Conected to DB " + dbName);
return con;
} // insertRecordsToDB
Exception in thread "main" java.lang.NoClassDefFoundError: oracle/dms/console/DMSConsole
at oracle.jdbc.driver.DMSFactory.<clinit>(DMSFactory.java:45)
at oracle.jdbc.driver.PhysicalConnection.createDMSSensors(PhysicalConnection.java:4203)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:629)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:218)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:29)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:538)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at
Just wondering in which jar has class oracle/dms/console/DMSConsole . Because when i checked those jars, this class is not available
The JDBC driver download page for Oracle 11g has the file ojdbc6dms.jar which contains oracle.jdbc.driver.DMSFactory.
EDIT: As per #JavaGeek's comment below, this jar does not actually contain the DMSConsole class. The required class is available in the Oracle Server installation, in the location $ORACLE_HOME/oc4j/lib/dms.jar. Server downloads are also available at Oracle TechNetwork

Set Oracle 10g database connection timeout in Java

I tried to set a connection timeout with the following code:
public class ConnectionTimeout {
public static void main(String[] args) throws Exception {
String entry = "jdbc:oracle:thin:#xxx:1521:xxx";
Connection con=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.setLoginTimeout(1);
con=DriverManager.getConnection(entry,"username","password");
Statement s=con.createStatement();
s.execute("select 1 from dual");
s.close();
con.close();
}
}
The instance xxx is not existing. But I get the following exception:
Exception in thread "main" java.sql.SQLException: E/A-Exception: Socket is not connected
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:255)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:387)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:439)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at my.package.connection.timeout.ConnectionTimeout.main(ConnectionTimeout.java:22)
How I can implement a timeout to an not existing or available Oracle database instance?
Edit:
If I set the DriverManager.setLoginTimeout(30); to 30 second, the exception happens so fast as before!
Your DriverManager.setLoginTimeout(1); sets the maximum time in seconds for the driver to wait while connecting to the database. In your case, it's set to 1.
To have no limit, set setLoginTimeout(0) where 0 means no limit.
I hope this helps.
Update if your instance xxx doesn't exists, how would you expect your Oracle Driver to connect to the database? It won't make any difference how long you set your loginTimeout there's not "host" to connect to.
Because, in Java doc, it shows: timeout in seconds, but in the implementation of JDBC Oracle, it is milliseconds.
You can try using a measure of milliseconds.

Categories

Resources