JDBC SQL Server Exception - java

I’m trying to connect a Java program with MS SQL SERVER 2012 but Java throws the exception: java.lang.ClassNotFoundException.
I understand that the problem often is a result of that the CLASSPATH is not set up correctly for the driver. I have followed the directions from Oracle to add a CLASSPATH, but I still get the same exception. When I type “echo %CLASSPATH%" in the command prompt I get a correct response. What have I missed?
Code:
import java.sql.*;
public class JDBCTest {
public static void main(String[ ] args) throws SQLException {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch(Exception e) {
System.out.println("Can't find database driver: " + e);
}
}
}

The runtime environment for your application may not contain the appropriate jar file.
The path that you have checked is only for your console environment. The application classpath is different from this.

Try this
public class connectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String Connectionurl="jdbc:sqlserver://localhost:1433;DatabaseName=YourDBName;user=UserName;Password=YourPassword"
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
String SQL = "";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
....
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
make sure that you download the driver jar file and put it at the right place

If Class.forName fails it is a problem of classpath.
try this code to check your classpath:
String classPath = System.getProperty("java.class.path");
String userDir = System.getProperty("user.dir");
System.out.println("Working Directory:");
System.out.println("\t"+userDir);
System.out.println("Classpath:");
String[] paths = classPath.split(";");
for (String path : paths) {
File pathFile = new File(path);
String check = pathFile.exists()?"OK ":"NOT-FOUND ";
System.out.println("\t"+check+path);
}

First of all download sqljdbc4.jar from here
Put this .jar in Your /WEB-INF/lib folder. (Check if this file appears from your eclipse's lib if not then Refresh Your Project)
And then run Your Project.

Related

Connect derby DB to Java

I wanted to connect DB to Java application in Intellij.
I set the classpath correctly, so that javac from cmd is working correct.
I have also downloaded all the jar files needed as a libary, but I still get java.sql.SQLException: No suitable driver found for jdbc:derby
What can be the problem?
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
final String DATABASE_URL = "jdbc:derby:myDB;create=true;user=user;password=pass";
try (
Connection connection = DriverManager.getConnection(DATABASE_URL, "user", "pass");
)
{
// ...
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
}
}
You can try if org.apache.derby.jdbc.EmbeddedDriver works. And it seems your connection url is wrong.
final String DATABASE_URL = "jdbc:derby://localhost:1527/myDB;create=true;user=user;password=pass";
Connection connection = null;
try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
connection = DriverManager.getConnection(DATABASE_URL );
}
catch (Exception e)
{
e.printStackTrace();
}

JDBC - java can't see installed drivers

I have a problem with JDBC drivers. I can't connect with my SQL Server database. Following code for test:
public class Test {
public static void main(String[] args) {
Connection con = null;
String conUrl = "jdbc:sqlserver://localhost:1433; databaseName=mydb; user=root; password=psswd;";
try {
con = DriverManager.getConnection(conUrl);
System.out.println("OK");
} catch (Exception e) { e.printStackTrace(); }
finally {
if (con != null) try { con.close(); } catch(Exception e) {}
}
}}
When i try run this code i still getting error:
java.sql.sqlexception no suitable driver found for (..)
I have added path to sqljdbc4.jar to classpath variable and enu\auth\x64 localization to Path variable. I'm working on JRE 1.8, SQL Server 2014 and Windows 7.
It's because you haven't loaded the driver. Just modify your existing code
try {
//this will load the driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(conUrl);
System.out.println("OK");
} catch (Exception e) { e.printStackTrace(); }
finally {
if (con != null) try { con.close(); } catch(Exception e) {}
}

How to connect JDBC to tns oracle

I can connect from plsql to database using tns file
Now I want to connect to the database from my Java using JDBC.
What I tried:
I search google and I find that I have to using this connection String:
"jdbc:oracle:thin:#//host:port))/tnsfile)";
My computer name is myPC
The port that is written in the tnsfile is 5151
So I tried this connection String
"jdbc:oracle:thin:#//myPC:5151))/tnsfile"
but I got this Exception
java.sql.SQLRecoverableException: IO ERROR: SO Exception was generated
What am I doing wrong?
How to connect my JDBC to the database using tns file?
You have to set a property named oracle.net.tns_admin to point to the location of the folder containing your tnsnames.ora file. Then you specify the entry from that file after the # sign in your DB URL. Check example below. You can find more information here: Data sources and URLs - Oracle Documentation
import java.sql.*;
public class Main {
public static void main(String[] args) throws Exception {
System.setProperty("oracle.net.tns_admin", "C:/app/product/11.2.0/client_1/NETWORK/ADMIN");
String dbURL = "jdbc:oracle:thin:#ENTRY_FROM_TNSNAMES";
Class.forName ("oracle.jdbc.OracleDriver");
Connection conn = null;
Statement stmt = null;
try {
conn = DriverManager.getConnection(dbURL, "your_user_name", "your_password");
System.out.println("Connection established");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT dummy FROM dual");
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (stmt != null) try { stmt.close(); } catch (Exception e) {}
if (conn != null) try { conn.close(); } catch (Exception e) {}
}
}
}
Example entry from tnsnames.ora file:
my_net_service_name=
(DESCRIPTION=
(ADDRESS=(some address here))
(CONNECT_DATA=
(SID=some_SID_name)))
Where my_net_service_name string is what you have to subsitite for ENTRY_FROM_TNSNAMES from my Java example.
Rather than hard code the path to tnsnames.ora, better to find it from the environment:
public static void setTnsAdmin() {
String tnsAdmin = System.getenv("TNS_ADMIN");
if (tnsAdmin == null) {
String oracleHome = System.getenv("ORACLE_HOME");
if (oracleHome == null) {
return; //failed to find any useful env variables
}
tnsAdmin = oracleHome + File.separatorChar + "network" + File.separatorChar + "admin";
}
System.setProperty("oracle.net.tns_admin", tnsAdmin);
}
Try the following:
System.setProperty("oracle.net.tns_admin", PATH_TO_TNSNAMES.ORA);
Class.forName ("oracle.jdbc.OracleDriver");
dbUrl = "jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST="+IPHOST+")(PORT="+PORT+"))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME="+DBNAME+")))"
conn = DriverManager.getConnection(dbUrl, USERNAME, PASSWORD);
Be sure to have the latest version of ojdbc.jar

Class not found loading JDBC org.postgresql.Driver

I'm working on a web project and I recently installed postgres 9.1.1
The postgresql server is up and running. I can connect via psql as usual and everything is loaded and properly saved from a dump of the db I made from 8.5.
So I also downloaded the JDBC4 driver for 9.1 postgres version here:
http://jdbc.postgresql.org/download/postgresql-jdbc-9.1-901.src.tar.gz
I added it to the java build path using the project properties via eclipse.
This is the code I use to provide db connection to other classes (i.e. it's a singleton, I get a new connection only if the existing is either closed or null, from one object at a time only)
public abstract class DBConnection {
private static Connection connection = null;
public static void connect() {
try {
if (connection == null) {
String host = "127.0.0.1";
String database = "xxxxx";
String username = "xxxxx";
String password = "xxxxx";
String url = "jdbc:postgresql://" + host + "/" + database;
String driverJDBC = "org.postgresql.Driver";
Class.forName(driverJDBC);
connection = DriverManager.getConnection(url, username,
password); //line firing the class not found exception
} else if (connection.isClosed()) {
connection = null;
connect();
}
} catch (SQLException e) {
e.printStackTrace(System.err);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public static void disconnect() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(
Level.SEVERE, null, e);
}
}
}
public static Connection getConnection() {
try {
if (connection != null && !connection.isClosed()) {
return connection;
} else {
connect();
return connection;
}
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE,
null, e);
return null;
}
}
#Override
public void finalize() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(
Level.SEVERE, null, e);
}
}
}
}
As I wrote in the title when I run the project and a class asks for a connection to this class I always get a Class Not Found Exception, Since it apparently can't load the org.postgresql.Driver.class The driver is located in a subfolder of the project ~/lib/org.postgresql-9.1-901.jdbc4.jar and as I said added to the build path via eclipse project properties.
I'm also providing a sample query to let see the usual behavior of my classes to access the DBConnection:
public static final User validateUserCredentials(String id, String pswd) {
Connection connection = DBConnection.getConnection();
Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE, (connection!=null)?"connection not null":"connection null");
Statement stmt = null;
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, "validating credentials for user: username : " + id + " password : " + pswd);
String sql = "Select * from fuser where id = '" + id + "'";
ResultSet resultset = null;
try {
stmt = connection.createStatement();
resultset = stmt.executeQuery(sql);
Logger.getLogger(Credentials.class.getName())
.log(Level.SEVERE, sql);
resultset.next();
String password = resultset.getString("pswd");
if (pswd.equals(password))
return new User(id, pswd);
} catch (SQLException ex) {
Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE,
null, ex);
} finally {
if (stmt != null)
stmt = null;
if (resultset != null)
resultset = null;
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
}
connection = null;
}
}
return null;
}
I'm working on a web project and I recently installed postgres 9.1.1
...
I added it to the java build path using the project properties via eclipse.
That's the wrong way. That JAR has to be dropped straight in /WEB-INF/lib folder of the web project without fiddling with the Build Path in the project's properties. That folder is standard part of webapp's runtime classpath.
Unrelated to the concrete problem: you've a major design flaw in your DBConnection class. You've declared Connection as static which essentially makes your connection not threadsafe. Use a connection pool and never assign the Connection (nor Statement nor ResultSet) as a class/instance variable. They should be created and closed in the very same try-finally block as where you're executing the query. Further you've there also a SQL injection hole. Use PreparedStatement instead of concatenating user-controlled variables in the SQL string.
See also:
JDBC MySql connection pooling practices to avoid exhausted connection pool
Get database connection from a connection pool
Am I Using JDBC Connection Pooling?
Add this dependency in your pom:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1203-jdbc4</version>
</dependency>
The first thing I'd do is unpack the jar and confirm that the driver is really in there as org.postgresql.Driver. I notice when looking at jarfinder and related sites that there isn't a Postgres 9.x jar containing org.postgresql.Driver.

how to install JDBC and how to use it to connect to mysql?

i am trying to install JDBC but i dont know how, when you only have the jar file, i copied it to my java ext folder but it keep giving me an error, can anyone show me how to complete install the driver and use it?
below is the codes that i used
import java.sql.*;
public class Test1
{
public static void main (String[] args)
{
String url = "jdbc:mysql://localhost:3306/sabayafr_sabmah";
String username = "root";
String password = "ma";
Connection connection = null;
try {
System.out.println("Connecting database...");
connection = DriverManager.getConnection(url, username, password);
System.out.println("Database connected!");
} catch (SQLException e) {
System.err.println("Cannot connect the database!");
e.printStackTrace();
} finally {
System.out.println("Closing the connection.");
if (connection != null) {
try {
connection.close();
} catch (SQLException ignore) {
}
}
}
}
}
And below is the Response that i get
Cannot connect to database server
Update # 3
C:\Users\AlAsad\Desktop>java -cp .;mysql-connector-java-5.0.8-bin.jar Test1
Connecting database...
Cannot connect the database!
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/
sabayafr_sabmah
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Test1.main(Test1.java:12)
Closing the connection.
You're trying to connect MySQL with the URL of a jTDS JDBC driver which is designed specifically for Microsoft SQL Server. This ain't ever going to work. Even not when you fix the current problem by placing the JAR file in classpath.
You really need the MySQL JDBC driver. Also see this answer for a short but complete tutorial
On the other hand, if you are using an IDE such as Netbeans or Eclipse you can add the jar file as a resource to the project.
You certainly have JDBC problems, but the exception isn't telling you that. Read it again:
Exception in thread "main" java.lang.NoClassDefFoundError: Test1
Caused by: java.lang.ClassNotFoundException: Test1
It's your Test1.class that it can't find, not the JDBC driver.
You should not be copying anything into the jre/lib/ext directory. That's for library extensions, not JDBC JARs. It wasn't meant as a crutch for people who don't understand how CLASSPATH works.
I'd write it more like the following. Those close methods will come in handy.
When I run it on my machine, adding the MySQL JDBC JAR to my CLASSPATH, I get the following result:
C:\java -classpath .\mysql-connector-java-5.1.6-bin.jar; persistence.utils.DatabaseUtils
product: MySQL
version: 5.1.24-rc-community
major : 5
minor : 1
Here is the source code:
package persistence.utils;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseUtils
{
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/contacts";
public static final String USERNAME = "contacts";
public static final String PASSWORD = "contacts";
public static void main(String[] args)
{
Connection connection = null;
try
{
String driver = ((args.length > 0) ? args[0] : DRIVER);
String url = ((args.length > 1) ? args[1] : URL);
String username = ((args.length > 2) ? args[2] : USERNAME);
String password = ((args.length > 3) ? args[3] : PASSWORD);
connection = getConnection(driver, url, username, password);
DatabaseMetaData metaData = connection.getMetaData();
System.out.println("product: " + metaData.getDatabaseProductName());
System.out.println("version: " + metaData.getDatabaseProductVersion());
System.out.println("major : " + metaData.getDatabaseMajorVersion());
System.out.println("minor : " + metaData.getDatabaseMinorVersion());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
close(connection);
}
}
public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
{
Connection connection = null;
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
return connection;
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement statement)
{
try
{
if (statement != null)
{
statement.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet resultSet)
{
try
{
if (resultSet != null)
{
resultSet.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void rollback(Connection connection)
{
try
{
if (connection != null)
{
connection.rollback();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
'I am trying to install JDBC'
You don't have to install JDBC. It is part of the JDK & JRE.
Try putting your .jar file in the classpath.
The library that contains the Driver (net.sourceforge.jtds.jdbc.Driver) needs to be on the classpath.
Assuming you start your application with
java Test1
then simply do
java -cp .;driver.jar Test1
where 'driver.jar' should be exchanged with the filename (relative or full path) of your database driver lib.
EDIT
A classpath tutorial will exceed the comments section below this question. Please take a cup of coffee and look at this page. It will most likely help you to continue.

Categories