java.sql.SQLNonTransientConnectionException Cannot load connection class because of underlying exception - java

New to JDBC and trying to connect to data base in MySql workbench. Following is the Java code
import java.sql.*;
public class Demo {
public static void main(String[] args) throws Exception
{
String url = "jdbc:mysql://localhost:3306//students?useSSL=false";
String user = "root";
String password = "root";
String query = "Select * from students";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rt = st.executeQuery(query);
rt.next();
String name = rt.getString("stu_name");
System.out.println(name);
st.close();
con.close();
}
}
Following is the error being thrown:
Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the main URL sections.
My MySQL workbench version is 8.0.21 with same version for mysql-connector/J

I assume the problem is the double slash (//) in your URL. Try
String url = "jdbc:mysql://localhost:3306/students?useSSL=false";
instead.

Related

How to resolve the jdbc connection error ? Why I can't fetch the table data from the mysql server?

import com.mysql.jdbc.Driver;
import java.sql.*;
public class JdbcDemo {
public static class jdbcTest
{
public static void main(String[] args) throws Exception
{
String url = "jdbc:mysql://localhost:3306/coffee_db";
String uname = "Jeep";
String pass = "random";
String query = "select * from customers;";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,uname,pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("query");
while (rs.next()) {
String name = rs.getString("first_name");
System.out.println(name);
}
st.close();
con.close();
}
}
Error:
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.
Exception in thread "main" java.sql.SQLException: Statement.executeQuery() cannot issue statements that do not produce result sets.
at enter code herecom.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1135)
at com.company.JdbcDemo$jdbcTest.main(JdbcDemo.java:22)
There are two issues:
Class.forName("com.mysql.jdbc.Driver"); - this JDBC driver is old and has been replaced by the stated new one. This is only a warning. This is not the cause of your problem.
You do not need to use Class.forName. Just remove that line. The correct driver will be used when you call DriverManager.getConnection, as long as you have the correct driver library in your classpath.
This statement:
ResultSet rs = st.executeQuery("query");
is trying to execute the query "query". But "query" is not a valid SQL query. You need to use the variable name instead:
ResultSet rs = st.executeQuery(query);
Can you try and replace
Class.forName("com.mysql.jdbc.Driver");
with
Class.forName("com.mysql.cj.jdbc.Driver");
I think that the name of the class that implements java.sql.Driver in MySQL Connector/J has changed from com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver.

SQLNonTransientConnectionException Connecting with MySQL in Eclipse

I am trying to write code for bringing a text file's data into a database using Eclipse, MySQL Workbench, and JDBC 8.0.11. It is giving me a ClassNotFoundException. I have looked at multiple other questions, and they have all been fixed by putting the java\com\mysql\jdbc\Driver.java inside the DriverManager.getConnection parameter. I have already done that, and it is still giving me an error. Anyone have any ideas as to why I'm still getting this error?
public static void main(String[] args) throws Exception{
Class.forName //Register JDBC Driver
("*mysql-connector-java-8.0.11.\\src\\legacy\\java\\com\\mysql\\jdbc\\Driver.java*")
.newInstance();
conn = DriverManager.getConnection (url, user, pass);
Statement stmt = conn.createStatement();
String mysql1 = "UPDATE Policy SET " + readAndArray //Changeable file path
("filepath");
}
NEW EDIT
Following #zlakad 's advice, it turns out that you don't need to use Class.forName() if you have Java 6 or higher. Although, now I have a new error: SQLNonTransientConnectionException because of the underlying WrongArgumentException. I'm puzzled as to why it does this because I'm not using the incorrect parameters for DriverManager.getConnection. Any suggestions?
String url = "file path"; //Changeable for MySQL DB
String user = "root";
String pass = "password";
public static void getConnection() throws Exception {
Connection conn = DriverManager.getConnection(url, user, pass);
Statement stmt = conn.createStatement();
Try this:
// None of this belongs in a main method.
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
// where are url, user, pass set? I don't see them.
Connection conn = DriverManager.getConnection(url, user, pass);
Statement stmt = conn.createStatement();
// this is simply wrong.
String mysql1 = "UPDATE Policy SET " + readAndArray("filepath");
}
You're new to Java and JDBC. This is not a good way to do it. I'd recommend that you search the web and SO for some examples of how to do it better.
You have to load driver class for connection not jar file of that class
you shoud try this:
Class.forName("com.mysql.jdbc.Driver");
I was using the wrong format for a database url in the DriverManager.getConnection();
I changed my url to a jdbc:mysql://host:3306/ and it worked.
String url = "jdbc:mysql://*host*:3306/";
Connection conn = DriverManager.getConnection(url, user, pass);

SQL Server Java driver not working in class path

I have written a simple Java file to handle some SQL that is integrated with SQL server.
I downloaded the appropriate driver and stored the JAR in the correct class path however it only works if I run the file directly.
I have tried calling methods within the sql class from another class and i get the following error:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
I understand that this issue is well documented but it doesn't address my unique problem which is that it works within the file but not externally.
Another issue is that after the program is closed and rebuild my program forgets that the JAR was added as a library and requires me to add it again which is not good.
I have tried adding the class path by manually copying and pasting it into an XML config file but this is a hacky solution and I would rather do it properly. Please let me know where I am going wrong.
<CLASSES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.ow2.asm/asm/5.0.4/da08b8cce7bbf903602a25a3a163ae252435795/asm-5.0.4.jar!/" />
<root url="jar://$USER_HOME$/IdeaProjects/r3prototypingCFS/contracts/src/main/kotlin/com/r3corda/protocols/sqljdbc42.jar!/" />
</CLASSES>
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Use jdts driver ..it work with Sql Server 2014.
pom.xml
<dependencies>
<!-- https://mvnrepository.com/artifact/net.sourceforge.jtds/jtds -->
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
and src
import java.sql.*;
public class Main {
public static void main(String[] args) throws SQLException {
// write your code here
Connection conn = null;
ResultSet rs = null;
String url = "jdbc:jtds:sqlserver://localhost:1433/DATABASENAME";
String driver = "net.sourceforge.jtds.jdbc.Driver";
String userName = "username";
String password = "yourpassword";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Connected to the database!!! Getting table list...");
Statement stmt = conn.createStatement();
String sql = "SELECT top 10 PhoneNumber,RegistrationDate\n" +
" \n" +
" FROM tblProductRegistration";
// ResultSet resultSet = stmt.executeQuery(sql);
// String selectSQL = "SELECT USER_ID, USERNAME FROM DBUSER WHERE USER_ID = ?";
//Statement stmt = conn.createStatement();
ResultSet resultSet = stmt.executeQuery(sql);
// preparedStatement.setInt(1, 1001);
// ResultSet resultSet = preparedStatement.executeQuery( );
//STEP 5: Extract data from result set
while(resultSet.next()){
//Retrieve by column name
String PhoneNumber = resultSet.getString("PhoneNumber");
String RegistrationDate = resultSet.getString("RegistrationDate");
//Display values
System.out.print("PhoneNumber: " + PhoneNumber);
System.out.print("RegistrationDate: " + RegistrationDate);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
rs.close();
}
}
}

Connecting to database on server

Edited:
I'm trying to connect to my database but I'm stuck.
I get the following error:
I have a mysql database and gain access to it using phpMyAdmin.
Here's my code (UPDATED):
public class DBConnection
{
static String user = "ademphotography_dk_financesjava";
public static String pass = "******";
private static String db = "ademphotography_dk_financesjava";
protected static String url = "jdbc:mysql://ademphotography.dk.mysql";
public static Connection getConnection()
{
Connection conn;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(url+"/"+db, user, pass);
return conn;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
I've tried using the IP of the host:
Protected static String url = "jdbc:mysql://XX.XX.X.XX:3306";
but that resulted in this error instead (but now I don't have problem with "unkown host"):
Caused by: java.net.ConnectException: Connection timed out: connect
Wouldn't this Java expression:
url+db
return this string:
jdbc://ademphotography.dk.mysqlademphotography_dk_financesjava
It seems like you need a literal slash character before the database name.
I'd expect that without the slash, that whole string "ademphotography.dk.mysqlademphotography_dk_financesjava" is going to be seen as a hostname.
The connection must be in the form
jdbc:mysql://server/database
In your example the line please update the following two lines:
protected static String url = "jdbc:mysql://ademphotography.dk.mysql";
...
conn = (Connection) DriverManager.getConnection(url+"/"+db, user, pass);
[edit: corrected a wrong line of code]

Class.forName error in Java connecting to SQL Database

I'm getting some kind of syntax error and I'm not sure how to resolve it or what I'm doing wrong exactly. I was following a tutorial on youtube, and I followed exactly how it was done in the video. I added the jar file to the project, but its still giving me this error. I'm fairly new to java and just trying to learn how to create a link between a java application and a sql database.
The error is on the line for:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Any help or hints is appreciated
package database_console;
import java.sql.*;
public class DBConnect {
String dbURL = "jdbc:microsoft:sqlserver://localhost:1433;databaseName=TestDB1";
String user = "sa";
String pass = "pass";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
try {
Connection myConn = DriverManager.getConnection(dbURL, user, pass);
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("Select * from Login");
while (myRs.next())
{
System.out.println(myRs.getString("Username"));
System.out.println(myRs.getString("Password"));
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
I haven't written anything into the main yet, what I've posted is the complete code I've done. Here are the error messages I'm getting:
Description Resource Path Location Type Syntax error on token ".", # expected after this token DBConnect.java /database_console/src/database_console line 11 Java Problem
Description Resource Path Location Type Syntax error, insert ")" to complete MethodDeclaration DBConnect.java /database_console/src/database_console line 11 Java Problem
Description Resource Path Location Type Syntax error, insert "Identifier (" to complete MethodHeaderName DBConnect.java /database_console/src/database_console line 11 Java Problem
Description Resource Path Location Type Syntax error, insert "SimpleName" to complete QualifiedName DBConnect.java /database_console/src/database_console line 11 Java Problem
First, ensure you are getting the jar from the correct place: https://msdn.microsoft.com/en-us/sqlserver/aa937724.aspx
Then, add it to your classpath. If you are using eclipse, press CTRL+SHIFT+T and type SQLServerDriver. It must find the class name.
Lastly, your code won't compile. Add the entire code you wrote inside the main method:
public class DBConnect {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String dbURL = "jdbc:microsoft:sqlserver://localhost:1433;databaseName=TestDB1";
String user = "sa";
String pass = "pass";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
try (Connection myConn = DriverManager.getConnection(dbURL, user, pass);
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("Select * from Login")) {
while (myRs.next()) {
System.out.println(myRs.getString("Username"));
System.out.println(myRs.getString("Password"));
}
}
}
}

Categories