java connect to backend explanation - java

I am super newer in java language. Now i am getting started java.
I am keen interst know about how to connect java with back end.
For that I have been installed oracle 11g express edition and sql developer.
First of all i just confused here, is these two tools are (oracle 11g express edition and sql developer.) enough for connect java with back end.?
And i am using jdk1.8.0_25 and eclipse editor.
If yes, means, what are the further process to achieve?
Already i know little bit about php, i did something connecting database, retrive the data from database..
So what is my goal is, what is the best way to connect backend with java?
Can anyone java expert explain step step by process?

Step 1 : Download Oracle JDBC Drivers
You can download Oracle JDBC drivers from here. Choose the version appropriate for your database version. In this example, I use the Oracle 11g JDBC driver since I connect to Oracle 11g database. There are two versions available for Oracle 11g, ojdbc5.jar (for JDK 1.5) and ojdbc6.jar (for JDK 1.6). Use appropriate version for your Java installation (Oracle now requires online registration for downloading drivers). I use ojdbc6.jar for this tutorial.
Step 2 : Java Program to Connect to Oracle
The following Java program uses Oracle JDBC driver to connect to a running Oracle database instance. You can use this program on any Oracle database as this example uses Oracle’s built-in dummy table DUAL for fetching system date. DUAL enables us to get values such as system date using a normal SQL query.
// Example Java Program - Oracle Database Connectivity
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class OracleSample {
public static final String DBURL = "jdbc:oracle:thin:#localhost:1521:XE";
public static final String DBUSER = "system";
public static final String DBPASS = "manager";
public static void main(String[] args) throws SQLException {
// Load Oracle JDBC Driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
// Connect to Oracle Database
Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
Statement statement = con.createStatement();
// Execute a SELECT query on Oracle Dummy DUAL Table. Useful for retrieving system values
// Enables us to retrieve values as if querying from a table
ResultSet rs = statement.executeQuery("SELECT SYSDATE FROM DUAL");
if (rs.next()) {
Date currentDate = rs.getDate(1); // get first column returned
System.out.println("Current Date from Oracle is : "+currentDate);
}
rs.close();
statement.close();
con.close();
}
}
Before you run the program ensure that you change the values for DBURL, DBUSER and DBPASS. DBURL is of the form,
jdbc:oracle:thin:#machinename:1521:databasename
Replace machinename with the name of the machine where oracle is running and replace databasename with service name of the database instance.
See this page for more details on JDBC API.
Step 3 : Add ojdbc.jar to Classpath
In order to compile or run the above program, you need to add ojdbc.jar to the classpath of your program. If you are using IDE such as NetBeans or Eclipse, you can add ojdbc.jar as a dependent library and NetBeans will automatically add it to classpath.
If you are running the above program from command line, copy ojdbc.jar to the folder where the above Java program is located and then compile the file using the following command (this adds ojdbc.jar to classpath),
javac -classpath ./ojdbc6.jar OracleSample.java
Run the Java program using the following command (ojdbc.jar is added to classpath),
java -classpath "./ojdbc6.jar;." OracleSample
Note that when you are running OracleSample, you need both the JDCB jar file and the current folder in the classpath.

Related

Connecting to remote SQL Server using SQL Driver in Java

Key notes:
Using SQL Server 2005
Using JDK 1.8
JDK 1.8 DOES NOT SUPPORT JDBC-ODBC Bridge ANYMORE
I have both Microsoft SQLJDBC 4.0 and 6.2 in my library
I am trying to connect to a remote SQL Server in Java for quite some time now and still have not been able to. I am hoping to connect using my DSN that I have created. The new driver JDK 1.8 uses needs a connection URL which I have created below. Everything in the code below looks correct. But I am still getting the error:
SEVERE: Java Runtime Environment (JRE) version 1.8 is not supported by this driver. Use the sqljdbc4.jar class library, which provides support for JDBC 4.0.
java.lang.UnsupportedOperationException: Java Runtime Environment (JRE) version 1.8 is not supported by this driver.
Use the sqljdbc4.jar class library, which provides support for JDBC 4.0.
Here is my code:
String connectionUrl = "jdbc:sqlserver://InterfaceDSN" +
"databaseName=DB_Local;Trusted_Connection=True;integratedSecurity=true";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
String SQL = "SELECT TOP 10 * FROM Person.Contact";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}catch (Exception e)
{
e.printStackTrace();
}
To conclude:
Knowing what I have and what I need, is there another way to connect to the database, I am running out of options here considering I am using JDK 1.8 with SQL Server 2005.
What is happening
As the message says:
java.lang.UnsupportedOperationException: Java Runtime Environment (JRE) version 1.8 is not supported by this driver.
Use the sqljdbc4.jar class library, which provides support for JDBC 4.0.
This is because JDBC4.0 has a lot of changes, meaning you need to use a newer version of the driver. You cannot run the old driver on the new version.
How to fix it
Using just 6.2 or version 6.2.2.jre8 should fix the issue.
Extra info
You shouldn't need the below code after JDBC 4.0 (Java 1.6+)
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Starting with the Microsoft JDBC Driver 4.2 for SQL Server, Sun Java
SE Development Kit (JDK) 8.0 and Java
You can read it here where you can find the requirements for the JDBC Driver.
So, you have to update your JDBC driver to v 4.2 at least. This is clear enough.

Unable to connect to SQL Server via JDBC. No suitable driver found for jdbc:sqlserver://

I simply want to use SQL Server database in my HTTP Servlet program but my program can't seem to connect to the database. It gives me the following error:
No suitable driver found for
jdbc:sqlserver://localhost:1433;databaseName=Bookyard;integratedSecurity=true;
This is my connection method.
package practice.bookyard.server.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Database {
public static Connection getConnection() {
String url = "jdbc:sqlserver://(LocalDb)\\MSSQLLocalDB:1433;databaseName=Bookyard;integratedSecurity=true;";
Connection connection = null;
try {
connection = DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
I had the sever name as localhost:1433 earlier but I changed it to the SQL Server instance name (LocalDb)\\MSSQLLocalDB:1433 but it still seems to pick up the old name.
Also, I am not sure how to provide the right connection string when connecting to SQL Server localdb.
I am using Eclipse for Java EE, Mars 2, and I downloaded Microsoft JDBC drivers for SQL 6.0 from this website.
I ran the installation, unzipped the contents of the resulting folder. Then, I added the sqljdbc42.jar file to the build path as I am targeting JDK 1.8.
UPDATE
Upon Scary Wombat's suggestion, I have also added the path to the sqljdbc42.jar file to my classpath.
However, I still get the same error.
I am pretty confident this is a reflection issue, in that the type loader isn't able to resolve the driver type from my connection string. Which means, the connection string syntax I am using is wrong.
I changed my connection string to read as follows:
String url = "jdbc:sqlserver://localhost:1433;
instance=(LocalDb)\\MSSQLLocalDB;
databaseName=Bookyard;integratedSecurity=true;";
However, I still not only get the same error but the exception message I receive still has my old connection string. So, clearly, there's also some caching going on, I just don't know where. Who is caching my connection string and how do I refresh / clear that cache?
Could you please tell me how to provide a SQL Server instance name if I am connecting to localdb and not on the main SQL Server instance?
As #ScaryWombat and #JozefChocholacek had hinted, it turned out to be a class path issue. Apparently, you have to copy and paste just the sqljdbc42.jar file, and this file only directly into the WEB-INF\lib folder and not within any sub-folder.
I did that it still gave me that error.
That was because the WEB-INF folder structure, when I viewed it in the Project Explorer, still had the old folder structure. So, I right-clicked on the WEB-INF folder in the Project Explorer and selected the Refresh command.
I also updated my environmental variable CLASSPATH to point it to the WEB-INF folder and that error went away.
you can do like below
String url = "jdbc:sqlserver://YOUR PC NAME;instanceName=SQLEXPRESS;DatabaseName=dbname;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection myCon = DriverManager.getConnection(url);
note :however its not necceaary for new version of jdbc driver to load driver class manually using class.forname

Java connect to a remote MS SQL server database

I am trying to connect to the database on the remote MS SQL server, using the provided connection string. The connection string is as follows:
data source=qsss.gar.de\SQL2012,3000;initial catalog=City;persist security info=True;user id=usr;password=usr##2009;
I understand I should have the suitable drivers, so I have downloaded the SQL Server drivers from microsoft.com/download/en/details.aspx?id=21599
, and added them to the build path of my project. Those are sqljdbc.jar and sqljdbc4.jar.
I am just using this test code to see if the connection is established.
public static void main(String[] args) throws Exception {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection connection = DriverManager.getConnection(
"qsss.gar.de\SQL2012,3000;initial catalog=City;persist security info=True;user id=usr;password=usr##2009;");
System.out.println("Connected!");
}
Doing so, I get an error: Java Runtime Environment (JRE) version 1.8 is not supported by this driver. Use the sqljdbc4.jar class library, which provides support for JDBC 4.0.
What am I doing wrong here?
Do not add both jars to your classpath since they both contain the com.microsoft.sqlserver.jdbc.SQLServerDriver-class and in your situation the program loads the one from sqljdbc.jar. Remove sqljdbc.jar from your classpath and only add sqljdbc4.jar so your program will always load the correct driver-version.

Conflict between Netbeans IDE 8.0 and UCanAccess?

I have to define a new Driver in the Netbeans "Services" Tab
Services->Databases->Drivers->new Driver...
because I want use the "Entity Classes from Database"-Wizard in context with UCanAccess.
1st step: "new Driver" does work (only declaration ;-) )
Driver File(s): f:\WorkspaceNetbeans\MSAccessDB\lib\UCanAccess-2.0.4-bin\ucanaccess-2.0.4.jar
Driver Class: net.ucanaccess.jdbc.UcanaccessDriver
Name:msaccess
2nd step: "Connect using..."
JDBC URL: jdbc:ucanaccess://F:/WorkspaceNetbeans/MSAccessDB/data/Datenbank2.accdb
"User Name" and "Password" leave blank
The "Test Connection"-Button results in Error Message:
Cannot establish a connection to
jdbc:ucanaccess://F:\WorkspaceNetbeans\MSAccessDB\data\Datenbank2.accdb using
net.ucanaccess.jdbc.UcanaccessDriver (Could not initialize class
net.ucanaccess.jdbc.UcanaccessDriver)
I've got the newest ucanaccess from http://ucanaccess.sourceforge.net/site.html
ucanaccess-2.0.4.jar, commons-lang-2.6.jar, commons-logging-1.0.4.jar, hsqldb.jar, jackcess-2.0.3.jar in the Netbeans Classpath.
The old fashion way to connect via jdbc to ucanaccess works fine.
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String connectString = "jdbc:ucanaccess://" + "f:/WorkspaceNetbeans/MSAccessDB/data/Datenbank2.accdb";
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn = DriverManager.getConnection(connectString, "", "");
conn.createStatement().execute("CREATE TABLE example1 (id COUNTER PRIMARY KEY,descr text(400), number numeric(12,3), date0 datetime) ");
}
The same connection string also works fine make DBeaver able to connect to the MSAccess db.
My set up:
Windows 7 Professional 64 bit
Microsoft Office 2013
NetBeans IDE 8.0
Java 1.8
The problem is similar to: "Conflict between JT400 and UCanAccess?" Conflict between JT400 and UCanAccess?
but the answers there don't help with my problem.
Any ideas to solve my problem?
UCanAccess 2.0.4.1 has been released, now you can configure UCanAccess as NetBeans service.
As explained in the UCanAccess web site (tab 'jdbc client tools') you have to:
-in the field Driver File(s), add ucanaccess.jar and all dependencies. I've upgraded the commons-logging in the UCanAccess distribution to the 1.1.1, so you can use that jar with NetBeans8.
-use the following pattern for the jdbc url:
jdbc:ucanaccess://;showschema=true
Showschema connection property must be setted to true.
I was wrong, it wasn't a tricky task but...
To establish the connection you have to list in the Driver File(s) :
ucanaccess-2.0.4.jar,
commons-lang-2.6.jar,
hsqldb.jar,
jackcess-2.0.3.jar
AND
a different version of commons-logging that you can find it in NetBeans:
NetBeans 8.0\ide\modules\org-apache-commons-logging.jar (the commons-logging in the UCanAccess distribution is in conflict with that used by NetBeans)
But unfortunatly, after establishing the connection, you won't be able to execute queries through this IDE, because of a trivial bug in the UcanaccessDatabaseMetadata which hasn't effect with the other IDE jdbc clients I tested (Openoffice, Libreoffice, DBeaver, Squirrel, SQLeo and so on) .
So, to do this, you have to wait some days (I think I'll post a patched Ucanaccess 2.0.4.1 next week). Also, I'll add a note about UCanAccess configuration as NetBeans service in the UCanAccess web site.

JDBC driver MS Access connection

I want connect my MS access file with Java GUI program,but I have problem with connection....
I have Windows 7 64b, and ms office 2007.
When I opened the ODBC driver manager in the control panel I havent found any driver for Microsoft Access (maybe when I started the ODBC is started running the 64bit ODBC, now I think is running the 32bit ODBC.
I read this and I make it :
"jdbc-odbc connection for window 7 64 bit machine..
1 . Right click Data source (ODBC)..go to properties change the folloing thing
target [ %SystemRoot%\SysWOW64\odbcad32.exe ]
start in : [ %SystemRoot%\System32 ]
press enter and continue as admin source: source link
"
) Now when I start in conctrol pannel the ODBC I can see the driver screenshoot
My program code(I tried two ways but I have same error):
public void Connect() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// String DatabaseFile = "D:java/Invertory.mdb";
// String DATABASE =
// "jdbc:odbc:Driver="
// + "{Microsoft Access Driver (*.mdb, *.accdb)};"
// + "DBQ=" + DatabaseFile;`enter code here`
String DATABASE ="jdbc:odbc:Driver= Microsoft Access Driver (*.mdb, *.accdb);DBQ=Invertory.mdb";
CONEX = DriverManager.getConnection(DATABASE);
} catch (Exception X) {
X.printStackTrace();
//JOptionPane.showMessageDialog(null,e);
}
}
error
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
Use UCanAccess JDBC Driver :
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://<mdb or accdb file path>",user, password);
for example:
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://c:/pippo.mdb");
So for your example it will be Connection conn=DriverManager.getConnection("jdbc:ucanaccess://"+path)
If you are using Windows 64-bit you probably need to go to this path
C:/Windows/SysWOW64/odbcad32.exe
Then I noticed that you are using the direct path instead creating new System DSN, your direct path is correct till the path to the access file you must give the full path like this :
jdbc:odbc:Driver= Microsoft Access Driver (*.mdb, *.accdb);DBQ=path/to/Invertory.mdb"
To get the path you probably need to use java.io.File that have a method returns the abslute path to the file see the example :
import java.sql.*;
public class TestConnection {
Connection con ;
Statement st ;
ResultSet rs ;
String db;
public TestConnection (){
try{
String path = new java.io.File("Invertory.mdb").getAbsolutePath();
db ="JDBC:ODBC:Driver=Microsoft Access Driver (*.mdb, *.accdb); DBQ="+path;
doConnection();
} catch(NullPointerException ex){
ex.printStackTrace();
}
}
public void doConnection(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(db);
st = con.createStatement();
rs = st.executeQuery("select * from Invertory");
while(rs.next()){
System.out.println(rs.getObject(1));
}
}catch(SQLException | ClassNotFoundException ex){
System.out.println(ex.toString());
}
}
public static void main(String...argS){
new TestConnection();
}
}
I answered a similar question enter link description here a while back.
Basically at that time:
You could connect to Ms-Access from 32 bit java through the JDBC-ODBC bridge
You could not connect to a 32 bit Odbc driver through the JDBC-ODBC from 64 bit java. There was a message telling you that you can only connect from a 32 bit programs
While Microsoft does provide a 64 bit Ms-Access driver, it did not work with Java's 64 bit JDBC-ODBC driver.
Since then there seems to be a new open-source Ms-Access JDBC Driver Ms-Access JDBC driver. I have no Idea how good it is.
You just missing something in your code right here :
db ="JDBC:ODBC:Driver=Microsoft Access Driver (*.mdb, *.accdb); DBQ="+path;
You need to add {} between Driver= and )=; .
Like this Below
db ="JDBC:ODBC:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ="+path;
final String fileName = "c:/myDataBase.mdb"
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="+fileName;
Connection con = DriverManager.getConnection(url,username,password);
The problem is that you should run on Java 32 bit try to install latest JDK and it will work
I run it using JDK version "jdk-7u67-windows-i586.exe"
On a 64 bit system, you should:
run as admin accessdatabaseengine_64.exe
run java - 7-64 bit - jre.
if you are working in NETBEANS then after unzipping ucanacess.zip file add all jar file in the classpath using property window of project click on compile tab and add jar file then compile and test app.
JDBC-ODBC MS-ACCESS CONNECTION STOPPED WORKING IN JDK8. I solved the issue by installing JDK7 along with JDK8 in the same PC, once installed JDK7 I assigned it as the JDK version to use in my project as follows in Netbeans:
1.RIGHT CLICK THE PROJECT IN THE LIST > CLICK PROPERTIES
2.CLICK LIBRARIES ON THE LEFT NAVIGATION TREE
3.CLICK BUTTON MANAGE PLATFORMS > CLICK BUTTON ADD PLATFORM...
4.FOLLOW WIZARD, DESPITE IT SHOWS JAVA STANDARD EDITION CLICK NEXT
5.NAVIGATE TO C:\Program Files (x86)\Java AND SELECT THE FOLDER OF JDK7 > CLICK NEXT
6.THE FIELD AUTOFILL WITH THE RIGHT INFO... > THEN CLICK FINISH
7.SELECT THE JDK PLATFORM FROM THE LIST > CLICK CLOSE > OK
8.JDK7 SHOULD SHOW IN LIBRARIES PACKAGE.
JDK7 in Libraries Package
Click Back in Browser to return here after looking at the image...
From here on everything must run smoothly.
Hope it solves your problem.
Thanks.

Categories