Java not connecting to MS Access database using Eclipse - java

Can anyone help me? I've already tried to solve this for one hour and I'm still confused.
Below is my code and i get this error when compiling.
Output msg::
DriverLoaded
Could Not Connect to Databasejava.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DBConnect.<init>(DBConnect.java:11)
at DBConnect.main(DBConnect.java:21)
Code::
import java.sql.*;
public class DBConnect {
public DBConnect() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("DriverLoaded");
String url = "jdbc:odbc:; DRIVER = Microsoft Access Driver (*.mdb, *.accdb); DBQ = DB.accdb";
Connection con = DriverManager.getConnection(url);
System.out.println("Connection Established Successfully");
} catch(Exception e) {
e.printStackTrace();
System.out.println("Could Not Connect to Database");
}
}
public static void main (String args[]) {
DBConnect dbcon = new DBConnect();
}
}

Overloaded methods for getConnection()
1)
getConnection( String url, Properties info )
url -
a database url of the form jdbc:subprotocol:subname
info -
a list of arbitrary string tag/value pairs as connection arguments;
normally at least a "user" and "password" property should be included
2)
getConnection( String url, String user, String password )
url - a database url of the form jdbc:subprotocol:subname
user -
the database user on whose behalf the Connection is being made
password -
the user's password
3) getConnection( String url )
url -
a database url of the form jdbc:subprotocol:subname
Considering you're using the last constructor, it seems your url syntax in incorrect. I'm not familiar with MS Access, but I'll offer a suggestion I found on another answer.
This is your syntax
"jdbc:odbc:; DRIVER = Microsoft Access Driver (*.mdb, *.accdb); DBQ = DB.accdb"
A correct syntax I found was
File f = new File("\\\\***\\***\\****\\***.accdb");
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + f.getAbsolutePath();
Looks like you have an unnecessary semicolon after odbc and an extra space. Maybe you want to try the above syntax and see what happens. I'm not sure about the file part, but you may want to look into it if your url still fails after making the semicolon/space fix.
Check out this question also for more info on another option Connection with username and password

below is the working code for your problem...
import java.sql.*;
public class DBConnect {
public DBConnect() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("DriverLoaded");
String url = "jdbc:odbc:instance";
Connection con = DriverManager.getConnection(url);
System.out.println("Connection Established Successfully");
} catch(Exception e) {
e.printStackTrace();
System.out.println("Could Not Connect to Database");
}
}
public static void main (String args[]) {
DBConnect dbcon = new DBConnect();
}
}
steps to be followed:
create an access database DB.accdb in any directory of your windows xp system.
open start > controlpanel > Performance and maintanance > Administrative Tools > Data sources (ODBC) >click System DSN tab > click add > choose Microsoft Access Driver (accdb,mdb) > give the name : instance , (since, getConnection("jdbc:odbc:instance") and click and browse the DB.accdb located in your hard drive ) press ok and restart your command prompt. and run the code again.
Running the same code in eclipse
create a java project.
add a main class and edit the source of this main class. just copy and paste the about code.
create a user library by adding the jar files from the jdk/bin directory.
link the build path to the project by linking the userlibrary.
run the project.

Related

Java database application is not connecting to the jdbc database even after including the jar file. How do I fix it? [duplicate]

How do you connect to a MySQL database in Java?
When I try, I get
java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
Or
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Or
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
Here's a step by step explanation how to install MySQL and JDBC and how to use it:
Download and install the MySQL server. Just do it the usual way. Remember the port number whenever you've changed it. It's by default 3306.
Download the JDBC driver and put in classpath, extract the ZIP file and put the containing JAR file in the classpath. The vendor-specific JDBC driver is a concrete implementation of the JDBC API (tutorial here).
If you're using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project's properties.
If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp or -classpath argument when executing your Java application.
java -cp .;/path/to/mysql-connector.jar com.example.YourClass
The . is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass and the ; is the classpath separator as it is in Windows. In Unix and clones : should be used.
Create a database in MySQL. Let's create a database javabase. You of course want World Domination, so let's use UTF-8 as well.
CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Create a user for Java and grant it access. Simply because using root is a bad practice.
CREATE USER 'java'#'localhost' IDENTIFIED BY 'password';
GRANT ALL ON javabase.* TO 'java'#'localhost' IDENTIFIED BY 'password';
Yes, java is the username and password is the password here.
Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax:
jdbc:mysql://hostname:port/databasename
hostname: The hostname where MySQL server is installed. If it's installed at the same machine where you run the Java code, then you can just use localhost. It can also be an IP address like 127.0.0.1. If you encounter connectivity problems and using 127.0.0.1 instead of localhost solved it, then you've a problem in your network/DNS/hosts config.
port: The TCP/IP port where MySQL server listens on. This is by default 3306.
databasename: The name of the database you'd like to connect to. That's javabase.
So the final URL should look like:
jdbc:mysql://localhost:3306/javabase
Test the connection to MySQL using Java. Create a simple Java class with a main() method to test the connection.
String url = "jdbc:mysql://localhost:3306/javabase";
String username = "java";
String password = "password";
System.out.println("Connecting database...");
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
If you get a SQLException: No suitable driver, then it means that either the JDBC driver wasn't autoloaded at all or that the JDBC URL is wrong (i.e. it wasn't recognized by any of the loaded drivers). Normally, a JDBC 4.0 driver should be autoloaded when you just drop it in runtime classpath. To exclude one and other, you can always manually load it as below:
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
Note that the newInstance() call is not needed here. It's just to fix the old and buggy org.gjt.mm.mysql.Driver. Explanation here. If this line throws ClassNotFoundException, then the JAR file containing the JDBC driver class is simply not been placed in the classpath.
Note that you don't need to load the driver everytime before connecting. Just only once during application startup is enough.
If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException: Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the other, follow the following advices:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
Note that closing the Connection is extremely important. If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. Always acquire the Connection in a try-with-resources statement. Or if you're not on Java 7 yet, explicitly close it in finally of a try-finally block. Closing in finally is just to ensure that it get closed as well in case of an exception. This also applies to Statement, PreparedStatement and ResultSet.
That was it as far the connectivity concerns. You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class.
Using a Singleton Pattern for the DB connection is a bad approach. See among other questions: Is it safe to use a static java.sql.Connection instance in a multithreaded system?. This is a #1 starters mistake.
DriverManager is a fairly old way of doing things. The better way is to get a DataSource, either by looking one up that your app server container already configured for you:
Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");
or instantiating and configuring one from your database driver directly:
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("scott");
dataSource.setPassword("tiger");
dataSource.setServerName("myDBHost.example.org");
and then obtain connections from it, same as above:
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
...
rs.close();
stmt.close();
conn.close();
Initialize database constants
Create constant properties database username, password, URL and drivers, polling limit etc.
// init database constants
// com.mysql.jdbc.Driver
private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
private static final String MAX_POOL = "250"; // set your own limit
Initialize Connection and Properties
Once the connection is established, it is better to store for reuse purpose.
// init connection object
private Connection connection;
// init properties object
private Properties properties;
Create Properties
The properties object hold the connection information, check if it is already set.
// create properties
private Properties getProperties() {
if (properties == null) {
properties = new Properties();
properties.setProperty("user", USERNAME);
properties.setProperty("password", PASSWORD);
properties.setProperty("MaxPooledStatements", MAX_POOL);
}
return properties;
}
Connect the Database
Now connect to database using the constants and properties initialized.
// connect database
public Connection connect() {
if (connection == null) {
try {
Class.forName(DATABASE_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL, getProperties());
} catch (ClassNotFoundException | SQLException e) {
// Java 7+
e.printStackTrace();
}
}
return connection;
}
Disconnect the database
Once you are done with database operations, just close the connection.
// disconnect database
public void disconnect() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Everything together
Use this class MysqlConnect directly after changing database_name, username and password etc.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class MysqlConnect {
// init database constants
private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
private static final String MAX_POOL = "250";
// init connection object
private Connection connection;
// init properties object
private Properties properties;
// create properties
private Properties getProperties() {
if (properties == null) {
properties = new Properties();
properties.setProperty("user", USERNAME);
properties.setProperty("password", PASSWORD);
properties.setProperty("MaxPooledStatements", MAX_POOL);
}
return properties;
}
// connect database
public Connection connect() {
if (connection == null) {
try {
Class.forName(DATABASE_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL, getProperties());
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return connection;
}
// disconnect database
public void disconnect() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
How to Use?
Initialize the database class.
// !_ note _! this is just init
// it will not create a connection
MysqlConnect mysqlConnect = new MysqlConnect();
Somewhere else in your code ...
String sql = "SELECT * FROM `stackoverflow`";
try {
PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
... go on ...
... go on ...
... DONE ....
} catch (SQLException e) {
e.printStackTrace();
} finally {
mysqlConnect.disconnect();
}
This is all :) If anything to improve edit it! Hope this is helpful.
String url = "jdbc:mysql://127.0.0.1:3306/yourdatabase";
String user = "username";
String password = "password";
// Load the Connector/J driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Establish connection to MySQL
Connection conn = DriverManager.getConnection(url, user, password);
Here's the very minimum you need to get data out of a MySQL database:
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/foo", "root", "password");
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM `FOO.BAR`");
stmt.close();
conn.close();
Add exception handling, configuration etc. to taste.
you need to have mysql connector jar in your classpath.
in Java JDBC API makes everything with databases. using JDBC we can write Java applications to
1. Send queries or update SQL to DB(any relational Database)
2. Retrieve and process the results from DB
with below three steps we can able to retrieve data from any Database
Connection con = DriverManager.getConnection(
"jdbc:myDriver:DatabaseName",
dBuserName,
dBuserPassword);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
You can see all steps to connect MySQL database from Java application here. For other database, you just need to change the driver in first step only. Please make sure that you provide right path to database and correct username and password.
Visit http://apekshit.com/t/51/Steps-to-connect-Database-using-JAVA
MySQL JDBC Connection with useSSL.
private String db_server = BaseMethods.getSystemData("db_server");
private String db_user = BaseMethods.getSystemData("db_user");
private String db_password = BaseMethods.getSystemData("db_password");
private String connectToDb() throws Exception {
String jdbcDriver = "com.mysql.jdbc.Driver";
String dbUrl = "jdbc:mysql://" + db_server +
"?verifyServerCertificate=false" +
"&useSSL=true" +
"&requireSSL=true";
System.setProperty(jdbcDriver, "");
Class.forName(jdbcDriver).newInstance();
Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
Statement statement = conn.createStatement();
String query = "SELECT EXTERNAL_ID FROM offer_letter where ID =" + "\"" + letterID + "\"";
ResultSet resultSet = statement.executeQuery(query);
resultSet.next();
return resultSet.getString(1);
}
Short and Sweet code.
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","root","");
//Database Name - testDB, Username - "root", Password - ""
System.out.println("Connected...");
} catch(Exception e) {
e.printStackTrace();
}
For SQL server 2012
try {
String url = "jdbc:sqlserver://KHILAN:1433;databaseName=testDB;user=Khilan;password=Tuxedo123";
//KHILAN is Host and 1433 is port number
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver Loaded");
conn = DriverManager.getConnection(url);
System.out.println("Connected...");
} catch(Exception e) {
e.printStackTrace();
}
Connection I was using some time ago, it was looking like the easiest way, but also there were recommendation to make there if statement- exactly
Connection con = DriverManager.getConnection(
"jdbc:myDriver:DatabaseName",
dBuserName,
dBuserPassword);
if (con != null){
//..handle your code there
}
Or something like in that way :)
Probably there's some case, while getConnection can return null :)
HOW
To set up the Driver to run a quick sample
1. Go to https://dev.mysql.com/downloads/connector/j/, get the latest version of Connector/J
2. Remember to set the classpath to include the path of the connector jar file.
If we don't set it correctly, below errors can occur:
No suitable driver found for jdbc:mysql://127.0.0.1:3306/msystem_development
java.lang.ClassNotFoundException: com.mysql.jdbc:Driver
To set up the CLASSPATH
Method 1: set the CLASSPATH variable.
export CLASSPATH=".:mysql-connector-java-VERSION.jar"
java MyClassFile
In the above command, I have set the CLASSPATH to the current folder and mysql-connector-java-VERSION.jar file. So when the java MyClassFile command executed, java application launcher will try to load all the Java class in CLASSPATH.
And it found the Drive class => BOOM errors was gone.
Method 2:
java -cp .:mysql-connector-java-VERSION.jar MyClassFile
Note: Class.forName("com.mysql.jdbc.Driver"); This is deprecated at this moment 2019 Apr.
Hope this can help someone!
MySql JDBC Connection:
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","Username","Password");
Statement stmt=con.createStatement();
stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("Select * from Table");
Short Code
public class DB {
public static Connection c;
public static Connection getConnection() throws Exception {
if (c == null) {
Class.forName("com.mysql.jdbc.Driver");
c =DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE", "USERNAME", "Password");
}
return c;
}
// Send data TO Database
public static void setData(String sql) throws Exception {
DB.getConnection().createStatement().executeUpdate(sql);
}
// Get Data From Database
public static ResultSet getData(String sql) throws Exception {
ResultSet rs = DB.getConnection().createStatement().executeQuery(sql);
return rs;
}
}
Download JDBC Driver
Download link (Select platform independent): https://dev.mysql.com/downloads/connector/j/
Move JDBC Driver to C Drive
Unzip the files and move to C:\ drive. Your driver path should be like C:\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19
Run Your Java
java -cp "C:\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19.jar" testMySQL.java
testMySQL.java
import java.sql.*;
import java.io.*;
public class testMySQL {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("show databases;");
System.out.println("Connected");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Connecting MSAccess database with java webapplication

I am trying to connect Msaccess database with my java webapplication using the following code:
import java.sql.*;
public class connection {
public static void main(String[] args) {
try {
// Load MS accces driver class
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("loaded");
String url = "jdbc:odbc:OnboardingTT";
System.out.println("assigned");
// specify url, username, pasword - make sure these are valid
Connection conn = DriverManager.getConnection(url,"","");
System.out.println("Connection Succesfull");
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}}}
But connection is not established. and the error is
loaded
assigned
Got an exception!
null
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.initialize(Unknown Source) at
sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
connect.connection.main(connection.java:18)
I also tried with
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb,*.accdb)};DBQ="+ "C:\\OnboardingTT.mdb";
Is this code correct or i have to do any changes in this please answer my question
Looks like something went wrong with the DB connection, maybe the DB is not online, maybe the user or the password are incorrect...
Please provide more info to help us to help you.
;-)

Java "Connection" Class does not connect to the DB

I'm trying to connect my DB with a Java Application i'm creating. What I got so far:
public class DBConnect {
public void DBConnect() {
try {
DBConnect DBConnect = null;
String url = "jdbc:mysql://localhost:3306/ähs_system";
String uName = "**";
String uPass = "**";
// Connection conn = DriverManager.getConnection(url, uName, uPass);
System.out.println("DB Connected");
}
catch (Exception Err) {
System.out.println("Error while connecting: " + Err.getMessage());
System.exit(0);
}
}
}
It's a runnable code although i'm still able to run the code without any error messages if I change my uName and/or Upass. So based on that information i'm gonna say that it's not actually connecting to the database at all...
Anyone with a few tips or tricks I can use?
I've loaded the DB in services and I am able to reach it and add data and run other SQL commands within netbeans but that's basically it. I've also loaded the mysql-connector-java-5.1.35 driver.
Run Code:
public static void main(String args[]) {
try {
DBConnect DBConnect = new DBConnect ();
DBConnect.DBConnect();
}
catch (Exception e){
System.out.println("Cannot connect to DB. Error: " + e.getMessage());
}
Let me know if you need any furthur information!
Updating property file: C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\build\built-jar.properties
Compiling 1 source file to C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\build\classes
C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\src\kiltenros\DBConnect.java:23: error: incompatible types: java.sql.Connection cannot be converted to kiltenros.Connection
Connection conn = DriverManager.getConnection(url, uName, uPass);
1 error
C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\nbproject\build-impl.xml:923: The following error occurred while executing this line:
C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\nbproject\build-impl.xml:263: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 0 seconds)
the error log is clear
java.sql.Connection cannot be converted to kiltenros.Connection
it seems that you imported the wrong class in the beginning of your class
DriverManager.getConnection(url, uName, uPass) return you instance of java.sql.Connection.
btw, change your local variable DBConnect to dbConnect so it won't has the same name as your class DBConnect and it will follow the java convention (lowercase on 1st letter of a variable)
I've very little experience with MySQL, but I avoid using "ä" in a database name. Perhaps, the underscore isn't allowed.
As per your stacktrace it seems you have not imported the correct Connection class. Delete the Connection file in your project and import java.sql.Connection.
The problem seemed to be a corrupted rs2xml.jar file. Once I reloaded it and it worked.

Connecting a Java application to an SQL database with Eclipse

I know this has been asked before but I really can't get this to work and as far as I can see I've followed all the steps.
I'm using Eclipse.
So I downloaded the Microsoft SQL Driver sqljdbc v4.0.
I created a new project and class. I edited the build path by adding the .jar file to the libraries.
I typed the following code:
package com.test.sql;
import java.sql.*;
public class Connect
{
public static void main (String[]args)
{
Connection con = null;
String conURL = "jdbc:sqlserver://localhost; databaseName=AnotherTestDB;";
try
{
con = DriverManager.getConnection(conURL);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I got the following error:
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost; databaseName=AnotherTestDB;
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.test.sql.Connect.main(Connect.java:11)
A bit more research and I was told put it in the java /lib/ext and reference it from there.
Nothing changed.
Any help?
Thanks.
Normally you need to register the driver before accessing to it:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Try with something like this:
String DRIVER = “oracle.jdbc.driver.OracleDriver”;
String DBURL = “jdbc:oracle:thin:#jiplc0.si.ehu.es:1512:Erreala”;
String UID = “USERNAME”;
String PWD = “PASSWORD”;
Driver kontrolatzailea = (Driver) (Class.forName(DRIVER).newInstance());
DriverManager.registerDriver(kontrolatzailea);
DefaultContext test = new DefaultContext(DBURL, UID, PWD, false);
DefaultContext.setDefaultContext(test);
Thanks for the responses.
I had both the sqljdbc4.jar and sqljdbc.jar referenced. The version of Java I am using requires that I use sqljdbc4.jar but it was being overwritten by sqljdbc.jar so I removed it.
I also changed my code to this:
public static void main (String[] args)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://nameMyLaptop//SQLEXPRESS";
Connection con = DriverManager.getConnection(connectionUrl);
}
//Insert catches
}
Apparently I didn't have to change the code but its not giving me that error now. I'm getting a new one but that's unrelated to my question.
Thanks for your time and responses.
You have to add the SQL JDBC Driver in your project libraries. download jtds.jar and add to your libraries. And follow the code below.
public static void main (String[] args) throws Exception{
Connection conn=null;
String url="jdbc:jtds:sqlserver://YourServerIp:1433/dbName";
String username="sa";
String password="****";
String driver="net.sourceforge.jtds.jdbc.Driver";
// Step 1: Load the JDBC driver.
Class.forName(driver);
// Step 2: Establish the connection to the database.
conn= DriverManager.getConnection(url, username,
password);
}
Here you have to follow two steps......

JDBC driver class not supported with sql server 2008

in my java code JDBC driver class is not supported with ms sql server 2008 while it works perfectly with ms sql server 2005
i have put jdbc driver class "com.microsoft.sqlserver.jdbc.SQLServerDriver"
MY CODE IS
import java.sql.*;
public class MysqlConnect{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:sqlserver://SQLSERVERIP:1433;";
String dbName = "DatabaseName=DBNAME";
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String userName = "sa";
String password = "password";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
while i am trying to connect it gives an error
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot open database "hj_cnb_ci
" requested by the login. The login failed.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError
(SQLServerException.java:197)
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(SQLServerC
onnection.java:2529)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConne
ction.java:1905)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServer
Connection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecu
te(SQLServerConnection.java:1893)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4615)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLSe
rverConnection.java:1400)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLSer
verConnection.java:1045)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConne
ction.java:817)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerCon
nection.java:700)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.
java:842)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at MysqlConnect.main(MysqlConnect.java:14)
plz help me to sort out this issue..
Please check your jdbc driver version. "Microsoft JDBC Driver 4.0" is suitable for your ms sql server 2008.
If you are using SQL Server 2008,please change your driver class to -- com.microsoft.jdbc.sqlserver.SQLServerDriver .The connection should work.
Check if exists "hj_cnb_ci " or DBName created it on your DB Server
Please check your database name. There is no need to call newInstance() when you load the class; it will call its static block and call the registerDriver() method of the Driver manager class, and will pass its reference as a parameter.
This method carries an object of the Driver class. When you call the driver manager's getConnection() method, interally it will call drivers class method connection with the help of that object.

Categories