ODBC Connection Setup in Java - java

I want to write a Java program that automates the work that the ODBC Data Source Administrator does in Windows.
That is, given an ODBC connection name and a path to the database on the hard drive, I want it to create the connection.
I really have no idea where to even begin with this. I looked at this but it said it was for C and I don't think that's very helpful. If anyone could point me in the right direction for this at all, I would appreciate it.
(I realize this question is REALLY vague, but that's all the information I was given.)

The answer to the question is that you don't need a registered DSN.
Here is an example of using a ODBC connection (not JDBC) from Java, using the system ODBC driver. Instead of editing the registry to create a registered DSN, your alternative is to use a un-registered DSN, like so:
Driver=sun.jdbc.odbc.JdbcOdbcDriver
Source=jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/Dir/DB/MyDB.mdb;
Or, using SQL Server:
Driver=sun.jdbc.odbc.JdbcOdbcDriver
Source=jdbc:odbc:Driver={SQL Server};SERVER=127.1;DATABASE=MyDB;UID=sa;PWD=mypass

All ODBC configuration is in Windows registry or odbc.ini in Linux (I haven't used ODBC on other platforms). At first you must create such configuration using ODBC manager, then check what was saved in configuration and write program that do the same. If you work with Windows 32 bit, then check registry at HKEY_LOCAL_MACHINE\SOFTWARE\ODBC.
Windows 64 bit have different configurations for 32 bit apps and 64 bit apps (just look for odbc.ini string in registry).
I think Java is not the best language to change something in Windows registry, but with Java you can create .reg text file that can be imported by regedit.exe, or you can use other language like Python with win32 extensions (Active Python has it by default).

You will want to look into using JDBC.

String driver ="sun.jdbc.odbc.JdbcOdbcDriver"
String url = "jdbc:odbc:Driver={Microsoft Access Text Driver (*.txt, *.csv)};DBQ=C:/CSVFolder
query = select * from myfile.csv

Check this one out..
Java Database Connectivity (JDBC) supports ODBC-based databases and provides a independent database.
Connection connection = null;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
connection = DriverManager.getConnection("connection string", "userName", "password" );
} catch (SQLException e) {
}
return connection;

I've never had to connect to MS SQL Server before. I've always used DB2 or Derby, MYSQL and everything was always the same for creating a connection. This is what I had to do for SQL Server.
private final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
url="jdbc:odbc:;DRIVER={SQL Server};SERVER="+server+","+port+";DATABASE="+dbName;
connection = DriverManager.getConnection(url,user,password);

Related

Connect Microsoft Access Database in Eclipse [duplicate]

Hi I have the below code to connect to MS Access database on Windows 7 OS. I have changed the Data Source short cut to point to 64bit odbc then 32 bit. But still getting the error as
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6956)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7113)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(JdbcOdbc.java:3072)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(JdbcOdbcConnection.java:323)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:174)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at TestDBConnection.main(TestDBConnection.java:21)
And my code is :
import java.sql.Connection;
import java.sql.DriverManager;
public class TestDBConnection {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
System.out.println("filename");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database =
"jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\\Test\\Tests.mdb";
Connection conn = DriverManager.getConnection(database, "", "");
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
How ever I have SQL Workbench tool through which I can connect to it but not through java code.
Please need help badly as I am struggling with this from past 3 hours searching on Google.
If your Java app is running in a 64-bit Java Virtual Machine (JVM) then DRIVER={Microsoft Access Driver (*.mdb)} is not going to work because there is no 64-bit version of the Jet database engine. You can...
Download and install the 64-bit version of the Microsoft Access Database Engine from here, and then use DRIVER={Microsoft Access Driver (*.mdb, *.accdb)} in your code.
... or ...
Run your Java app in a 32-bit JVM and continue to use the existing DRIVER= string. The related answer here might prove helpful if you choose this option.
... or ...
Use the UCanAccess JDBC driver for Access databases. It is a free, open-source, pure Java implementation so it works on both 32-bit and 64-bit systems, both Windows and non-Windows. It also works with Java 8 (which has dropped the JDBC-ODBC Bridge). For more details, see:
Manipulating an Access database from Java without ODBC
You can install the 64 ODBC drivers for Access available from Microsoft
http://www.microsoft.com/en-us/download/details.aspx?id=13255
1) you will have to configure System dsn (Driver Microsoft Access Driver(.mdb,.accdb))
2) link .mdb database in above configuration
and write below code.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:systemdsnname";
Connection conn = DriverManager.getConnection(database, "", "");

Java, SQL Database Connection

I am C# developer and I don't know much about Java, normally in C# when I wanna connect to a database I use the following command:
static SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
I read a tutorial about making database connection (Sql Server 2008) in java in MSDN saying that the address must be declared this way:
String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=JavaDB;user=UserName;password=*****";
I would like to if there's any way to declare the url the way I do in C#, I mean instead of
"jdbc:sqlserver://localhost:1433;"
I directly point to the database
"AttachDbFilename=|DataDirectory|\Database.mdf;"
thanks
The first part of the URL is prescribed by the JDBC specification, so all drivers will follow the structure jdbc:<vendor-identifier>:<vendor-specific-url>.
In Java creating the connection (at least via java.sql.DriverManager) is independent of the actual Driver implementation that creates the connection (in C# you create a typed vendor-specific connection).
The first part, jdbc:<vendor-identifier> is used as a selection mechanism so a Driver can quickly decide if it will accept an URL or not. Technically multiple driver implementations could accept an URL and create the connection. The <vendor-identifier> is usually the name of the database or company.
The <vendor-specific-url> will usually follow normal URL conventions (MS SQL Server JDBC URLS are an exception to that).
The format of the Microsoft JDBC driver is:
jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
See: Building the Connection URL.
Technically, Microsoft could have allowed only the database name in their <vendor-specific-url> and imply that it uses localhost but they decided not to do that.
The official documentation of the SQL JDBC driver does not mention any such thing
http://msdn.microsoft.com/en-us/library/ms378428.aspx
http://msdn.microsoft.com/en-us/library/ms378672(v=sql.110).aspx
so I assume it is not possible

jdbc odbc connection using password with ms access

I am trying to make connection in jdbc with MS Access. The connection is being established successfully but it's not taking the password in the connection string. I am using the following code.
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String connquery="jdbc:odbc:Driver={Microsoft Access Driver(*.mdb)};
DBQ=d:/newfolder/db11.mdb";
Connection c=DriverManager.getConnection(connquery,"","securityserver");
Statement st=c.createStatement();
}
catch(Exception ex)
{
ex.printStackTrace();
}
This connection is working properly without password but after applying the password it's throwing an exception.
You've been at this for days. Honestly, it's not that hard to connect to a relational database using Java.
I don't know what the deal is with Microsoft Access. I've used it before on small problems with minor success, but I wouldn't recommend it now that there are so many other alternatives available.
MySQL or PostgreSQL are probably beyond you, but I'd say you'll have better luck with the Derby database that's built into the JDK.
The JDBC-ODBC driver is a problem; it's not available if you're on a 64 bit OS. Access is for individual use; I wouldn't trust it for shared access. You're having problems with passwords; others won't be so reluctant to accept a password.
Change your database if you can and see if that helps.

Java JDBC - How to connect to Oracle using tnsnames.ora

tnsnames.ora file contains the Databases and the their description (host + port).
Is it possible to establish a connection relying on the file mentioned above? (Say by providing only the DB name):
In order to find this file, I have to know the default oracle home I need to check in the windows registry for HKEY_LOCAL_MACHINE\Software\Oracle and then to have all the KEY_XXX files and then check which one appears first on the %PATH%. Is there a way to automatically find this file on the client computer?
I wasn't even aware that using tnsnames with the thin driver is possible, but apparently it was added somewhere in version 10:
http://docs.oracle.com/cd/B19306_01/java.102/b14355/urls.htm#BEIDIJCE
In particular:
Note:
When using TNSNames with the JDBC Thin driver, you must set the oracle.net.tns_admin property to the directory that contains your tnsnames.ora file.
java -Doracle.net.tns_admin=%ORACLE_HOME%\network\admin
As mentioned, I haven't checked if this actually works.
I don't think that the "find the actual network config directory" logic is available via some Oracle function. You'll have to do it manually as outlined in your question, or maybe rely on the TNS_ADMIN environment variable being present. In that case, the java invocation would be
java -Doracle.net.tns_admin=%TNS_ADMIN%
Well, in some GUIs the TNS driver configuration is simply not implemented or not working (NetBeans for example :-) )
https://netbeans.org/bugzilla/show_bug.cgi?id=231526
There is simple workaround here. You can take the entry directly from the tnsnames.ora file and attach it to the jdbc driver string as following:
Example from using odbc7.jar (Oracle 12c JDBC driver for JDK 7) to
connect to Oracle 11gR2 RAC cluster:
jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=
TCP)(HOST=hostA)(PORT=
1522))(ADDRESS=(PROTOCOL=TCP)(HOST=hostB)(PORT=1521)))(SOURCE_ROUTE=yes)(CONNECT_DATA=(SERVICE_NAME=DatabaseService)))
Be aware of putting double :: characters in the end as host:port:service, if you will put :: in the end like this:
jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=
TCP)(HOST=hostA)(PORT=
1522))(ADDRESS=(PROTOCOL=TCP)(HOST=hostB)(PORT=1521)))(SOURCE_ROUTE=yes)(CONNECT_DATA=(SERVICE_NAME=DatabaseService)))::
You will end up with "NL Exception was generated" exception.
Another approach is to configure following property:
System.setProperty("oracle.net.tns_admin","C:/app/product/11.2.0/client_1/NETWORK/ADMIN");
Of course, instead of hardcoded value, you can for example set up environment variable in your operating system like ORACLE_TNS_ADMIN and then reference it:
System.setProperty("oracle.net.tns_admin",System.getenv("ORACLE_TNS_ADMIN"));
or pass it to java process via -D switch
on linux:
-Doracle.net.tns_admin=$ORACLE_TNS_ADMIN
and windows:as
-Doracle.net.tns_admin=%ORACLE_TNS_ADMIN%
Once our application is aware of TNS config file, we can connect by reference service name in TNSNAMES.ora file as in this full example:
// tell the driver where to look for the TNSNAMES.ORA file
System.setProperty(
"oracle.net.tns_admin",
"C:/app/product/11.2.0/client_1/NETWORK/ADMIN");
// ORCL is net service name from the TNSNAMES.ORA file
String dbURL = "jdbc:oracle:thin:#ORCL";
// load the driver
Class.forName("oracle.jdbc.OracleDriver");
Connection conn = null;
Statement stmt = null;
try {
conn = DriverManager.getConnection(dbURL,
"your_username",
"your_password");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT dummy FROM dual");
Starting from 18.3, TNS_ADMIN that provides the location of the tnsnames.ora file can be passed as part of the connection URL. Please note the syntax.
jdbc:oracle:thin:#jdbctest_medium?TNS_ADMIN=/test/cloud/network
Firstly make sure that SQL Developer software is properly installed in your machine. If you are using thin driver, ensure that your ojdbcX.jar file is in your build path. The steps to connect to Oracle data source using TNS Alias name are:
Set System Property for oracle.net.tns_admin. This should point to the directory which has your tnsnames.ORA file
System.setProperty("oracle.net.tns_admin", DIRECTORY_PATH_TO_TNSNAME.ORA_FILE);
Register an Oracle driver
DriverManager.registerDriver(new OracleDriver());
Create a connection object
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:username/password#TNS_ALIAS_NAME");
This should establish the Database connection.
You can also try the following
Try this, after some hours of troubleshooting came across a sample which I modified and it works like a gem.
jdbc:oracle:thin:#(description=(address_list=(address=(protocol=tcp)(port=1521)(host=19.16.200.12)) (address=(protocol=tcp)(port=1521)(host=19.16.200.10)))(load_balance = yes)(connect_data=(SERVICE_NAME=stackdb)))
A none load balance sample is given Below:
jdbc:oracle:thin:#(description=(address_list=(address=(protocol=tcp)
(port=1521)(host=prodHost)))(connect_data=(INSTANCE_NAME=ORCL)))
Here is the URL that helped https://docs.oracle.com/cd/E11882_01/java.112/e16548/jdbcthin.htm#JJDBC28202

Connecting to a MySQL database

I have created a MySQL database. I am building a GUI in java. How can I connect this Java software to the database?
First, you need to add the mysql jdbc driver jar to your project, then you would create a connection as follows:
String url = "jdbc:mysql://yourhost:port/dbname";
Class.forName ("com.mysql.jdbc.Driver"); // to load the driver
Connection conn = DriverManager.getConnection (url, userName, password);
Here yourhost is the name or ip address of the server, port is the port number to which the mysql server is bound, dbname is the name of your database.
using any of the miriad of Java/SQL API, so you can perform normal SQL queries. JDBC is a start
Start using JDBC, it's best for start. Take a look on some tutorials
http://www.tutorialspoint.com/jdbc/jdbc-quick-guide.htm
http://www.jdbc-tutorial.com/
this post has helped me quite alot!
I'm quite 'disapointed' and 'suprised' I suppose that Java doesn't have the fuctionatly of connected to online databases built in.
One thing that would make it better, and please tell me the followings true: the fact that users of my software don't have to do anything special like install any drivers?
I've already added one answer - asking a question but the comments/reply's I got seem to be a bit off topic and now I've commented back asking for the answer to my original question no one seems to be answering (Have a look for your self - see what I mean)
So, the orignal question :: The only thing I want to know;
Do the users of my software I made using JDBC have to do anything special regarding JDBC, or is just me who needs to have JDBC while writting the program?
PS Sorry if I'm a bit pushy or doing things that your not supposed to do - I'm new to this community!

Categories

Resources