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
Related
I'm trying to run some application and get the following error:
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for
JDBC]Can't start a cloned connection while in manual transaction mode.
I know that I should add the parameter ;SelectMethod=Cursor to your JDBC URL
But I'm having problem understanding where exactly should I change it? Should it be some conf file in JDBC driver folder somewhere? Or can I do it from sql management studio?
Also is there some easy way to determine if and what version of JDBC driver I have?
Help is very much appreciated!
You specify the URL when creating your JDBC connection, e.g.:
Connection con = DriverManager.getConnection(
"jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]",
username,
password);
Of course you have to replace the stuff in the brackets with your values.
Quite the same is true for every other tool (e.g. IntelliJ, Eclipse) I know of that connects to a DB via JDBC. See e.g. attached screenshot. Here you also specify the connection parameters via the JDBC URL.
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
I want to establish a connection to my MySQL database from my Java EE web application so I can query it from it. I added mysql-connector-java-5.1.14-bin.jar to my WEB-INF/lib folder.
Now when I try to establish a connection it says:
No suitable driver found for jdbc:mysql://localhost?autoReconnect=true.
The lines in my code where the error occurs are:
m_url = "jdbc:mysql://" + mDatabaseHost +"?autoReconnect=true";
m_connection = DriverManager.getConnection(m_url, mDatabaseUser, mDatabasePassword);
User and password are correct. What might be wrong?
I tested this with Tomcat 7.0.
I think that you forgot to initialize driver.
You have to say something like the following: Class.forName("com.mysql.jdbc.Driver"); bofore connecting to DB.
Try to add the database name after localhost and ensure that you don't have skip-networking in the my.cnf file
UPDATE
Put the Connector Jar into $CATALINA_HOME/lib
I want to access a database using a connection string that is given by a third party application. I have one example configuration that has a connection string like the following:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\path\to\theDatabase.mdb;Persist Security Info=False
Calling
DriverManager.getConnection("jdbc:odbc:" + connectionString);
gives me an SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
The third party application can access the database without problems.
The OS is Windows XP Service Pack 3 and up to date.
The msjet40.dll in system32 folder has version 4.0.9511.0 (up to date according to http://support.microsoft.com/kb/239114/en-us)
The file exists and I can access it using jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};C:\path\to\theDatabase.mdb
I just don't know what I'm doing wrong.
Problem is in your odbc connection
To connect access database try following
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:connSource");
goto ControlPanel->AdministrativeTools->DataSource(ODBC)->System DSN->ADD->MicrosoftAccess->
then in the name field give the Source Name as connSource.
you have to use this name instead of database name in your DriverManager.getConnection method.
Because getConnectionMethod take the source name not the database name. so your code is not working.
This might be a problem. I don't know of any JDBC drivers for OLE DB data sources. Here on SO this questions sits without answers from March: https://stackoverflow.com/questions/5184046/jdbc-oledb-bin .
Refer to the wesite below it contains connection strings of all variants for all the databases
http://www.connectionstrings.com/
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);