Connecting a Java application to an SQL database with Eclipse - java

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......

Related

SQL Server conecction with jdbc eclipse

I have the following code to connect to my database in SQL Server:
public static void main (String [] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://DESKTOP-G8057U8\\SQLEXPRESS:1433;databaseName=Vaporizadores;integratedSecurity=true;";
DBConection=DriverManager.getConnection(url);
DBStatement = DBConection.createStatement();
System.out.println("Conexion exitosa");
}catch(ClassNotFoundException | SQLException e) {
System.out.println("Conexion fallida");
}
}
when I run it I get "Conexion fallida", meaning that an exception was catched. I've tried different urls but I still can't connect to my DB. I know very little about jdbc and sql server, so it may be a stupid error.
It worked like this:
String url = "jdbc:sqlserver://DESKTOP-G8057U8;databaseName=Vaporizadores;integratedSecurity=true;";
and i added the sqljdbc_auth.dll to Java bin folder

Showing error-no suitable driver found for jdbc:oracle:thin:#localhost:1521:orcl

I am using jdk1.8 and I am trying to execute a jdbc program manually on oracle 8i. My code is compiling without any error but at the run time its showing error-no suitable driver found for jdbc:oracle:thin:#localhost:1521:orcl. I have already set the class path for jar file. I am using ojdbc7.jar file.
My code is:
import java.sql.*;
class Database
{
public static void main(String arg[])
{
try
{
String url="jdbc:orcl:thin:#localhost:1521:orcl";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(url,"scott","tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from aj1");
while(rs.next())
{
System.out.println("\n"+rs.getInt(1)+" "+rs.getString(2));
}
}
catch(Exception e){e.printStackTrace();}
}
}
Kindly give the solution for this:
You url String must be
String url="jdbc:oracle:thin:#localhost:1521:orcl";
instead of
String url="jdbc:orcl:thin:#localhost:1521:orcl";
and try.

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.

Java database connection issue

I have the following issue with my code :
import java.sql.*;
public class App {
public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306" ;
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{ System.out.println("Eroare incarcare driver!\n" + e);
return;
}
try{
Connection con = DriverManager.getConnection(url);
// Golim tabelul persoane
String sql = "DELETE FROM persoane";
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
stmt.execute("CREATE DATABASE IF NOT EXISTS test");
stmt.execute("USE test");
i get the exception...any idea how i can make this work? thx.
enter code here
You need to download and add the jdbc connector to your classpath.
http://dev.mysql.com/downloads/connector/j/
java.lang.ClassNotFoundException occured due to "class not found" in your project/war/ear. Exception is very self explanatory, How to solve it.
In your case:
Add com.mysql.jdbc.Driver driver class/jar in your build/deployment/lib path you can
download it HERE
Read here
Offical
Make sure you have the MySQL driver on your application classpath.
Change
Connection con = DriverManager.getConnection(url);
to
Connection con = DriverManager.getConnection(url,"username","password");
and replace it with yourusername and password

Java not connecting to MS Access database using Eclipse

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.

Categories