im trying to create a connection to the MSSQL08 database on my computer :
this is my simple piece of code :
public class JavaApplication2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws ClassNotFoundException {
String userName ="username";
String password ="password";
String url ="jdbc:microsoft:sqlserver://localhost; databaseName=Lando";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
try {
Connection conn = DriverManager.getConnection(url, userName, password);
} catch (SQLException ex) {
Logger.getLogger(JavaApplication2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
i get this Error :
SEVERE: null java.sql.SQLException: No suitable driver found for
jdbc:microsoft:sqlserver://localhost; databaseName=Lando at
java.sql.DriverManager.getConnection(DriverManager.java:596) at
java.sql.DriverManager.getConnection(DriverManager.java:215) at
javaapplication2.JavaApplication2.main(JavaApplication2.java:34)
when i change the URL to this : "jdbc:sqlserver://localhost; databaseName=Lando"
then i get this Error :
SEVERE: Java Runtime Environment (JRE) version 1.7 is not supported by
this driver. Use the sqljdbc4.jar class library, which provides
support for JDBC 4.0. Exception in thread "main"
java.lang.UnsupportedOperationException: Java Runtime Environment
(JRE) version 1.7 is not supported by this driver. Use the
sqljdbc4.jar class library, which provides support for JDBC 4.0. at
com.microsoft.sqlserver.jdbc.SQLServerConnection.(SQLServerConnection.java:304)
at
com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1011)
at java.sql.DriverManager.getConnection(DriverManager.java:571) at
java.sql.DriverManager.getConnection(DriverManager.java:215) at
javaapplication2.JavaApplication2.main(JavaApplication2.java:34)
I added the sqldjbc4.jar file to the project libraries in neatbeans, i also set the CLASSPATH in enviroment variables to the directory of the Microsoft Driver.
what could be the problem ?
Related
I recently switched to intellij but I'm finding it hard to connect to my localDB. The same code worked on eclipse fine. Also I have already added the sqljdbc42.jar as a module dependency.
package com.enter;
import java.sql.*;
public class SqlConnect {
private String username, password, url;
public Connection conn;
public SqlConnect() {
username = "user=admin;";
password = "password=admin";
url = "jdbc:sqlserver://Bossman-PC\\SQL2014TRAINING;databaseName=EnterDB;";
Connect();
}
public SqlConnect(String user, String pass) {
username = user;
password = pass;
url = "jdbc:sqlserver://Bossman-PC\\SQL2014TRAINING;databaseName=EnterDB;";
Connect();
}
public void Connect() { //Loads sql driver and creates a connection object with local database
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = url + username + password;
conn = DriverManager.getConnection(connectionUrl);
System.out.println("Connected.");
} catch(Exception e) {
e.printStackTrace();
}
}
public Connection getConnection() {
return conn;
}
}
Error produced:
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:4098)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:3160)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$100(SQLServerConnection.java:43)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:3123)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1981)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1628)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1459)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:773)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1168)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:678)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:252)
at com.enter.SqlConnect.Connect(SqlConnect.java:25)
at com.enter.SqlConnect.<init>(SqlConnect.java:12)
at com.enter.Login.makeConnection(Login.java:26)
at com.enter.Login.<init>(Login.java:16)
at com.enter.Execute.initLogin(Execute.java:14)
at com.enter.Execute.main(Execute.java:9)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.DatatypeConverter
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
... 19 more
Process finished with exit code 1
Any help would be greatly appreciated. I've also tried the overloaded DriverManager.getConnection(url, user, pass) method and same error.
For Java 9+ compatibility, you need to use version 6.4.0 or higher for the Java version you use as identified by the jreXX version suffix. Use the highest version lower or equal to you Java version).
Previous answer
As noted by Microsoft on GitHub:
Currently none of our driver released Jars are compatible with JDK9.
You can either switch to using the Java 8 JDK, or you can incorporate Microsoft's development code from their 'JDBC4.3' branch into your project and use that with the Java 9 JDK.
You can get this to work if you include the extra jvm parameter
--add-modules=java.se.ee
Which in your run configuration in Intellij would go here
This then includes several modules which in java 9 have been marked as deprecated for future removal so these could be removed in java 10 so it is only really a temporary solution until Microsoft release java 9 compatible jdbc drivers.
More on this can be found in the Java9 Migration guide
If you have a maven build, add the following to your pom.xml
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
This question already has answers here:
Failed to obtain JDBC Driver for MySQL under Tomcat environment
(2 answers)
Closed 6 years ago.
I have the code as below, which worked perfectly fine when I ran it as a Java Application:
package com.LearnersLingoo.WebContent;
// Consider all the necessary imports are taken care
public class VerifyUser {
public VerifyUser(){
}
boolean userExist(String userName, String userPassword){
return true;
}
public static void main(String[] args) throws SQLException {
Connection myConn = null;
Statement myStmt = null;
ResultSet myRes = null;
try{
myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "student", null);
System.out.println("Connection Successful");
myStmt = myConn.createStatement();
int rowsAffected = myStmt.executeUpdate("insert into learners" +
"(ID, userName, FirstName, LastName, Password)" +
"values" +
"(11001, 'Test', 'testUser', 'UserLastN', 'password')");
System.out.println("Rows inserted: " + rowsAffected);
}
catch (Exception e){
e.printStackTrace();
}
}
}
The console message is as below:
Connection Successful
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '11001' for key 'PRIMARY'
Here anyway the user is already present, so atleast the connection is successful.
When I have the similar code run as a Servlet I am getting
Connnnection not successfuljava.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
I have gone through other similar questions on this topic which suggested me to add class.forname( com.mysql.jdbc.driver ) But it did not help
#WebServlet
public class HomePage extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection connection;
/**
* #see HttpServlet#HttpServlet()
*/
public HomePage() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void init(){
try {
// Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "student", null);
System.out.println("Connection Successful");
} catch (SQLException e) {
System.out.println("Connnnection not successful");
e.printStackTrace();
}
}
Kindly help me on how to add the JDBC jar on Tomcat server. I am running Tomcat server for my web application in Eclipse installed on Mac.
Updated full stack trace:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.LearnersLingoo.WebContent.HomePage.init(HomePage.java:37)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:779)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:133)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
Connnnection not successful
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
I am able to resolve this issue by doing this:
I added the MySQL JDBC jar file to Tomcat Server using Tomcat Server "Open Launch Configuration" --> ClassPath. This resolved the issue.
Could you please tell me if this is the correct way to resolve the issue ?
So in total, I added the JDBC driver at two places.
1) To the web application classpath
2) to the Tomcat server classpath
You don't need to add the JAR in both the places, the best practice is to make it available to the respective web application's classpath (i.e., WEB-INF/lib).
Also, rather than adding it manually, ensure that your build tool (Maven, Gradle, etc) packages all required dependencies for you to the project's lib folder. So, when you deploy the project into the server, the JAR will be available in the respective lib folder.
This has something to with the ($CATALINA_HOME/lib)
As I have not configured the environment variable $CATALINA_HOME. I have to add the jdbc driver to the server classpath that I am running my local code which is the Tomcat web container.
So adding the mySQL JDBC jar file to Tomcat Server using Tomcat Server "Open Launch Configuration" --> ClassPath. This resolved the issue.
So in total I added the JDBC driver at two places. 1) To the web application classpath and 2) to the Tomcat server classpath
Actually adding the driver to the web application class path is not required. As this is already taken from the server classpath first.
I'm doing a Proof-of-Concept (PoC) Java reporting project in which I'm connecting to a SSL-enabled Oracle database from my workstation, using JDBC Thin driver. As the database is SSL-enabled, I added all the required certificates into a Oracle Wallet and provided its location in the Java code. The certs were also added cacert of the JRE. Java code excerpt -
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("ERROR: Oracle JDBC Driver not found");
e.printStackTrace();
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
String oracleURL = "jdbc:oracle:thin:#(DESCRIPTION(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCPS)(HOST=<hostname>)(PORT=2484)))(CONNECT_DATA=(SERVICE_NAME=<service>)))";
// Provide user ID, password for schema
Properties props = new Properties();
props.setProperty("user", "<user id>");
props.setProperty("password", "<password>");
// Setting properties for SSL
props.setProperty("oracle.net.ssl_cipher_suites", "(ssl_rsa_export_with_rc4_40_md5, ssl_rsa_export_with_des40_cbc_sha, SSL_DH_anon_WITH_3DES_EDE_CBC_SHA, SSL_DH_anon_WITH_RC4_128_MD5,SSL_DH_anon_WITH_DES_CBC_SHA)");
props.setProperty("oracle.net.ssl_client_authentication", "false");
props.setProperty("oracle.net.ssl_version", "3.0");
props.setProperty("oracle.net.encryption_client", "REJECTED");
props.setProperty("oracle.net.crypto_checksum_client", "REJECTED");
props.setProperty("javax.net.ssl.keyStore", "C:\\APP\\ORACLE\\product\\11.2.0\\client_1\\ewallet.p12");
props.setProperty("javax.net.ssl.keyStoreType","PKCS12");
props.setProperty("javax.net.ssl.keyStorePassword","Password1");
try {
connection = DriverManager.getConnection(oracleURL, props);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
System.out.println("Error code: " + e.getErrorCode());
System.out.println("SQL State: " + e.getSQLState());
e.printStackTrace();
return;
}
I'm able to compile the program and also run it using the following -
java -cp z:\jdk1.7.0_13\bin\ojdbc14.jar;z:\jdk1.7.0_13\bin OracleConnCheck
where:
z:\jdk1.7.0_13\bin\ojdbc14.jar - location of ojdbc14.jar
z:\jdk1.7.0_13\bin - Java classpath
OracleConnCheck - Java class
But I always encounter IO error accompanied with NL exception or SO exception. I checked out the Oracle and few articles related to the same exception in here but none addressed my exact problem. Could someone help? Thanks!
Edit: Adding the stacktrace -
Oracle JDBC Driver Registered!
Connection Failed! Check output console
Error code: 17002
SQL State: null
java.sql.SQLException: Io exception: NL Exception was generated
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:113)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:147)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:257)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:389)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:454)
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:802)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:190)
at OracleConnCheck.establishConnection(OracleConnCheck.java:51)
at OracleConnCheck.main(OracleConnCheck.java:72)
------- The End -------
Make sure you use the latest 12.1.0.2 JDBC drivers. You can download from OTN. Also, you need to include osdt_core.jar and osdt_cert.jar.
Refer to SSL with Oracle JDBC whitepaper for more details.
"NL Exception was generated" indicates that there is a format error in the connection string. In your case you are missing = after DESCRIPTION.
While trying to cennect HPQC from a 64bit machine(having 64bit JAVA, and ECLIPSE), I am getting the below mentioned exception:
Exception in thread "main" com4j.ExecutionException: com4j.ComException: 80040154 CoCreateInstance failed : Class not registered : .\com4j.cpp:153
at com4j.ComThread.execute(ComThread.java:203)
at com4j.Task.execute(Task.java:25)
at com4j.COM4J.createInstance(COM4J.java:97)
at com4j.COM4J.createInstance(COM4J.java:72)
at com.qc.ClassFactory.createTDConnection(ClassFactory.java:16)
at com.java.Test.main(Test.java:25)
Caused by: com4j.ComException: 80040154 CoCreateInstance failed : Class not registered : .\com4j.cpp:153
at com4j.Native.createInstance(Native Method)
at com4j.COM4J$CreateInstanceTask.call(COM4J.java:117)
at com4j.COM4J$CreateInstanceTask.call(COM4J.java:104)
at com4j.Task.invoke(Task.java:51)
at com4j.ComThread.run0(ComThread.java:153)
at com4j.ComThread.run(ComThread.java:134)
PFB my code:
public static void main(String[] args) {
// TODO Auto-generated method stub
//QC url
String url = "https://qc_link/qcbin";
//username for login
String username = "username";
//password for login
String password = "password";
//domain
String domain = "domain";
//project
String project = "project";
ITDConnection itdc = ClassFactory.createTDConnection();
System.out.println("Connecting");
itdc.initConnectionEx(url);
itdc.connectProjectEx(domain, project, username, password);
System.out.println("Connected......");
}
}
The above code works fine for 32bit Java and Eclipse.
Any help would be highly appreciated.
Regards,
Parag
The COM API's are 32-bit only and cannot be accessed by a 64-bit process. I have the same problem with .NET applications where I'm stuck in 32-bit until I can move to the REST API (which is bit-less) or host my COM-reliant code in an external process.
This issue can be solved by registering all 3 .dll files in c:\Windows\SysWow64. instead of c:\Windows\System32.
Hope it might be helpful:)
I use Ubuntu & Net-beans. I make a java desktop database application from Netbeans wizard. I use MySQL database which I can open & run query from its Services → Databases. When I run it I got the Exception below. When I clean & Build the Project run jar file, same Exception. I have installed Windows in the same machine dual boot way, and also have the same MySQL database & Java. When I run the jar file I make using Ubuntu Netbeans, it perfectly run in Windows and show the database data. I did the other way also, I make the same java application in Windows Netbeans using the same database and it run perfectly both withing the Netbeans and jar file. But when I try to run it in Ubuntu, both in Netbeans & jar file show the below Exception.
[TopLink Info]: 2012.01.29 11:16:58.898--ServerSession(285416048)--TopLink, version: Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))
Jan 29, 2012 11:16:59 AM org.jdesktop.application.Application$1 run
SEVERE: Application class customerrecordsu.CustomerRecordsUApp failed to launch
Local Exception Stack:
Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Error Code: 0
at oracle.toplink.essentials.exceptions.DatabaseException.sqlException(DatabaseException.java:305)
... lot of more
Caused by: java.net.SocketException: Can't connect to SOCKS proxy:Connection refused
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:427)
... lot of more
Below is part of 'my.cnf' file removing comments.
[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0
[mysqld]
user = mysql
socket = /var/run/mysqld/mysqld.sock
port = 3306
skip-external-locking
bind-address = 127.0.0.1
below is part of persistance.xml file
<property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/MyBusinessRecords"/>
<property name="toplink.jdbc.user" value="root"/>
<property name="toplink.jdbc.password" value="password"/>
Netbeans wizard use JPA, & Top Link. I make a program without wizard by pure Java, it worked perfectly in Ubuntu as expected and show the database data. That program is below. Both above and below use same Java MySQL connector.jar.
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
int id = 0;
String name = null;
try {
String url = "jdbc:mysql://localhost:3306/MyBusinessRecords";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, "root", "5843");
if (con != null) {
System.out.println("A database connection has been establised!");
st = con.createStatement();
rs = st.executeQuery("select * from COUNTRIES");
while(rs.next()){
id = rs.getInt(1);
name = rs.getString(2);
System.out.println("id = " + id + " Name = " + name);
}
}
} catch (Exception e) {
System.out.println("Problem" + e.toString());
} finally {
if (con != null) {
try {
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println(e.toString());
}
con = null;
}
}
}
This is my system
java version "1.7.0_01"
Java HotSpot(TM) 64-Bit Server VM (build 21.1-b02, mixed mode)
Ubuntu 11.10. OS type 64 bit
MySQL Version- MySQL 5.1.58-1ubuntu1
MySQL Client Version 5.1.58
Socket: /var/run/mysqld/mysqld.sock
I read the Q & A more then 15 in this site with same question, but that now one helped me. Please help me.
String url = "jdbc:mysql://localhost:3306/MyBusinessRecords";
Caused by: java.net.SocketException: Can't connect to SOCKS proxy:
a non-existant SOCKS proxy
bind-address = 127.0.0.1
You can try bind-address = 0.0.0.0 or jdbc:mysql://127.0.0.1:3306/MyBusinessRecords"
Try Java 1.6. I had a similar issue and changed back to Java 1.6 (I had upgraded to 1_7) and the issue went away. Probably need a different toplink or OracleDriver release for 1_7.