Question has been updated (The DriverManager is no longer loaded manually and instead the getConnection() method is used):
package guii;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* This program demonstrates how to establish database connection to Microsoft
* SQL Server.
* #author www.codejava.net
*
*/
public class JdbcSQLServerConnection {
public static void main(String[] args) {
Connection conn = null;
try {
String dbURL = "jdbc:sqlserver://ASUS\\YES:1433";
String user = "TestingUser";
String pass = "12345";
conn = DriverManager.getConnection(dbURL, user, pass);
if (conn != null) {
DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
System.out.println("Driver name: " + dm.getDriverName());
System.out.println("Driver version: " + dm.getDriverVersion());
System.out.println("Product name: " + dm.getDatabaseProductName());
System.out.println("Product version: " + dm.getDatabaseProductVersion());
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
The problem is the resulting Exception of this code. I can't find out know the reason why that particular exception is thrown.
The username, password and servername were double checked and they are definitively correct.
Currently this exception is thrown:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'TestingUser'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:246)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:83)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2532)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:1929)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:1917)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4026)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1416)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1061)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:833)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:716)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at guii.JdbcSQLServerConnection.main(JdbcSQLServerConnection.java:25)
Trouble Shooting Notes
Use integratedSecurity=true again
Check if you have the sqljdbc_auch.dll in your system32 folder
Check out this link
Make sure you use the correct one (32 vs 64 bit)
Make sure the sqljdbc_auch.dll is in the Windows system path
Check if the properties of your Server instance are set correctly: access rights, make sure it actually listens in the port 1433, ...
check out this link and don't just look at the accepted answer but the other two as well.
make sure your firewall does not prevent any connections
check out if your Java Version matches the jdbc Version you use sqljdbc4.2 needs Java 1.8, jdbc4.1 needs java 1.7. look here
Related
Project details:
| mysql-connector-java version : 8.0.27 |
| JDK version : 15.0.1 |
I am unable to make a connection to the MySQL database hosted on docker using Java. I have attached my code below for reference.
Note : I am able to make a connection to the database using python instead of java while making no changes to the connection details whatsoever. This problem only persists with java.
`
import java.sql.*;
public class TestJDBCMySQL
{ public static void main(String[] args)
{ String url = "jdbc:mysql://localhost/workson";
String uid = "retracted";
String pw = "retracted";
try ( Connection con = DriverManager.getConnection(url, uid, pw);
Statement stmt = con.createStatement();)
{
ResultSet rst = stmt.executeQuery("SELECT ename,salary FROM emp");
System.out.println("Employee Name,Salary");
while (rst.next())
{ System.out.println(rst.getString("ename")+","+rst.getDouble("salary"));
}
}
catch (SQLException ex)
{
System.err.println("SQLException: " + ex);
}
}
}
`
What I've done so far :
Creating a new user and granting all privileges using MySQL workbench
Verifying credentials. I was able to connect to the database using the docker cli with the exact same credentials.
Ensuring the database exists ( it does )
Add the mysql-connector-java to the reference library in VsCode
Specifying the port in the connection URL
I've added Ubuntu 20.04 under AD Domain controller and have installed MsSQL Server on Ubuntu machine.
My sqlcmd localhost works perfectly with windows authentication
$ sqlcmd -S localhost
1> select ##version
2> GO
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Microsoft SQL Server 2019 (RTM-CU10) (KB5001090) - 15.0.4123.1 (X64)
Mar 22 2021 18:10:24
Copyright (C) 2019 Microsoft Corporation
Developer Edition (64-bit) on Linux (Ubuntu 20.04.2 LTS) <X64>
(1 rows affected)
1>
Now, I'm trying to connect it with Simple Java code as
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* This program demonstrates how to establish database connection to Microsoft
* SQL Server.
*
*/
public class JdbcSQLServerConnection {
public static void main(String[] args) {
Connection conn = null;
try {
String dbURL = "jdbc:sqlserver://170.18.xx.xx:1433;integratedSecurity=true";
String user = "sa";
String pass = "*****************";
conn = DriverManager.getConnection(dbURL, user, pass);
if (conn != null) {
DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
System.out.println("Driver name: " + dm.getDriverName());
System.out.println("Driver version: " + dm.getDriverVersion());
System.out.println("Product name: " + dm.getDatabaseProductName());
System.out.println("Product version: " + dm.getDatabaseProductVersion());
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
I ran this source code as
java -cp mssql-jdbc-8.4.1.jre8.jar:sqljdbc4.jar:. -Djava.library.path=mssql-jdbc_auth-8.4.1.x64.dll JdbcSQLServerConnection
It throws exception as Caused by: java.lang.UnsatisfiedLinkError: no mssql-jdbc_auth-8.4.1.x64 in java.library.path
I found below few unanswered threads but not sure if they have added their machines under any DC
no mssql-jdbc_auth-8.4.1.x64 in java.library.path
no mssql-jdbc auth-8.4.1.x64 in java.library.path on linux
https://github.com/microsoft/mssql-jdbc/issues/1453
Seems like this is long requested answer, I finally able to connect to MsSQL Server 2019 installed on Ubuntu 20.04
what all I need is to use below syntax of DB URL and I don't need to pass any DLL or auth file.
"jdbc:sqlserver://172.18.44.171:1433;integratedSecurity=true;authenticationScheme=javaKerberos;authentication=NotSpecified";
I simply ran
java -cp mssql-jdbc-8.4.1.jre8.jar:. JdbcSQLServerConnection
Please refer this discussion here Connect To SQL Server With Windows Authentication From A Linux Machine Through JDBC
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 7 years ago.
I have searched the internet trying to find solutions on using java and JDBC to connect to MySQL. Unfortunately I have found multiple answers and none that solved my problem.
I downloaded the JDBC from MySQL, and unzipped the file to find the .jar. I placed the .jar in my C:/Program Files (X86)/Java/JDK.../JRE/lib/ext folder. I set my environmental variable classpath (maybe CLASSPATH, ClassPath ??) to the following:
%CLASSPATH%;.;C:\Program Files (x86)\Java\jdk1.8.0_65\jre\lib\ext
I use the script I composed based on all the different solutions I have seen to get this:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySql {
public static void main(String[] args)
{
Connection con = getConnection();
if (con != null) {
System.out.println("Connection Made");
}
else {
System.out.println("Connection not made");
}
}
private static Connection getConnection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila", "java", "java");
System.out.println("Connection Made");
conn.close();
}
catch (SQLException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
catch (ClassNotFoundException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
return con;
}
}
It compiles with javac MySql.java. Then when it runs (java MySql) I get com.mysql.jdbc. I have read that I don't need to register the driver, but when I remove Class.forName all I get is 'cannot find JDBC driver' error.
I can't narrow down my problem to either:
1). Classpath not setup correctly.
2). Improper java connection code.
3). Unable to locate MySQL server.
Any help would be appreciated.
Edit -
I placed the .jar file onto Desktop for testing purposes. Changed system classpath variable:
%CLASSPATH%;.;C:\User\User\Desktop\mysql-connector-java-5.1.38-bin.jar
Then when I add the trace for the error statement I get:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass<Unkown Source>
at java.lang.ClassLoader.loadclass (Unknown source)
at sun.misc.Launcher$AppClassLoader.loadclass(Unkown Source)
etc.
etc.
edit 2 - I have spent two days using Connect Java to a MySQL database as a resource and none of the instructions I have followed have solved my problem.
Instead of
System.out.println(e.getMessage());
Do this
e.printStackTrace();
You will see that the exception is:
java.lang.ClassNotFoundException: com.mysql.jdbc
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 MySql.getConnection(MySql.java:24)
at MySql.main(MySql.java:10)
Remove the Class.forName. You might get an access denied or some other error but it will solve the ClassNotFoundException. Here is the final edited version that should work:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySql {
public static void main(String[] args)
{
Connection con = getConnection();
if (con != null) {
System.out.println("Connection Made");
}
else {
System.out.println("Connection not made");
}
}
private static Connection getConnection() {
Connection con = null;
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila", "java", "java");
System.out.println("Connection Made");
conn.close();
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(0);
}
return con;
}
}
If you need Class.forName() you have to use correct class:
Class.forName("com.mysql.jdbc.Driver");
But with JDBC 4 that has become no longer needed.
Create full Exception stack traces and use the result to search here - most common errors have been solved here before.
NoSuitableDriverFound is a very strong indication your mysql-connector.jar (not the .zip....) is missing from your classpath when you run your code.
You could try like this:
Run java -cp .;C:\User\User\Desktop\mysql-connector-java-5.1.38-bin.jar MySql
I think you must add the path including the jar file name of the driver in your classpath. Like so:
%CLASSPATH%;.;C:\Program Files (x86)\Java\jdk1.8.0_65\jre\lib\ext\mysql-connector-java-xxx.jar
If your Java is version 6 or above you doesn't need Class.formName(...) code.
And for ensure that everything works, compile and execute your code in the follow way.
To compile:
java -cp PATH_TO_DRIVER; YOUR_CLASS.java
To execute:
java -cp PATH_TO_DRIVER; YOUR_CLASS
Change YOUR_CLASS to the name of your class and PATH_TO_DRIVER to the path where you download the MySQL driver.
Hope it helps!
Try this code!
public static void main(String[] argv) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/yourSCHEMAname,"login", "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!");
}
}
}
I wish to use jdbc to connect to a remote mysql database that has recently been secured via ssl. I found a simple example java program to test the connection. The connection fails and complains that the keystore file can not be found. I verify that the keystore is indeed where I say it is in the code. At least I think I do. The test application looks like this:
import java.io.File;
import java.sql.*;
public class TestMySQLSSL {
public static void main (String[] args)
{
Connection con = null;
System.getProperties().setProperty("javax.net.debug","all");
System.getProperties().setProperty("javax.net.ssl.keyStore","c:\\LiferayStuff\\bundles\\liferay-portal-6.0.6\\tomcat-6.0.29\\jrel.6.0_20\\keystore");
System.getProperties().setProperty("javax.net.ssl.keyStorePassword","####");
System.getProperties().setProperty("javax.net.ssl.trustStore","c:\\LiferayStuff\\bundles\\liferay-portal-6.0.6\\tomcat-6.0.29\\jrel.6.0_20\\truststore");
System.getProperties().setProperty("javax.net.ssl.trustStorePassword","####");
try
{
String url = "jdbc:mysql://xxx.xxx.xxx.xxx:3306/isc"+
"?verifyServerCertificate=true"+
"&useSSL=true"+
"&requireSSL=true";
String user = "*******";
String password = "******";
Class dbDriver = Class.forName("com.mysql.jdbc.Driver");
boolean filelives;
filelives = new File("c:/LiferayStuff/bundles/liferay-portal-6.0.6/tomcat-6.0.29/jre1.6.0_20/keystore").exists();
System.out.println("keystore " + filelives);
con = DriverManager.getConnection(url, user, password);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (con != null)
{
try
{
con.close();
}
catch (Exception e){}
}
}
}
}
the first bit of the output I get looks like this:
keystore true
keyStore is : c:/LiferayStuff/bundles/liferay-portal-6.0.6/tomcat-6.0.29/jrel.6.0_20/keystore
keyStore type is : jks
keyStore provider is :
default context init failed:java.security.PrivilegedActionException:java.io.FileNotFoundException: c:\LiferayStuff\bundles\liferay-portal-6.0.6\tomcat-6.0.29\jrel.6.0_20\keystore (The system cannot find the path specified)
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlyingexception:
** BEGIN NESTED EXCEPTION **
com.mysql.jdbc.CommunicationsException
MESSAGE: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
The keystore file is there but I suspect there may be something wrong with it. I am running the application on windows. Are there perhaps permission issues with the file? Any help would be appreciated.
Regards,
Dave Semeraro
It turns out the database admin had blocked all but a single ip access to the server. Once my IP was added I was able to get the code above to work. Sorry for wasting everyone's time.
I'm using MySQL 5.5 with its defaults. I created a user/password and ran a script creating a database called employees. Through the command prompt I can access the database:
mysql -u user -p
SELECT * FROM employees
In my Java application, I am unable to connect. I have tried these URLs, as well as others, but nothing works:
"jdbc:mysql://localhost/employees" "user" "password"
"jdbc:mysql://localhost:3306/employees" "user" "password"
"jdbc:mysql:///employees?user=user&password=password"
Here's the relevant code:
public Main()
{
try {
connection = DriverManager.getConnection(url);
//connection = DriverManager.getConnection(url, user, password);
// I don't know what else to try
} catch (SQLException ex) {
System.out.print(ex + "\n\n");
}
}
Make sure you have Mysql driver jar in the class path and check MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/connector-j-usagenotes-basic.html
The error tells me that either
ConnectorJ driver is not in your classpath.
OR
When using DriverManager, the jdbc.drivers system property has not been populated with the location of the Connector/J driver.
OR
The format of your connection URL is incorrect, or you are referencing the wrong JDBC driver.
In your scenario, it is the list item #1 which is the cause of the issue you are facing.
I would use something like below code snippet to get the connection object.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Connection conn = null;
...
try {
conn =
DriverManager.getConnection("jdbc:mysql://localhost/employees?" +
"user=user&password=password");
// Do something with the Connection
...
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}