Java, SQL Database Connection - java

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

Related

Why does MySQL database access require a forward slash in the server url?

I've been learning about databases access using Oracle and MySQL and found this interesting difference.
String dbURL1 = "jdbc:oracle:#serverName:port:database";
verses
String dbURL1 = "jdbc:mysql://serverName:port:/database";
Why the slash? If I don't provide the slash for MySQL, compiler is unable to determine a suitable driver. However, for Oracle, if I do provide a slash, the compiler also produces an error.
The URL format is defined by the Driver.
For MySQL you can check the full URL format here.
The format of connection string in JDBC is not mandated by the standard. Each DB driver is free to decide on its own format, based on the preferences of the designers. Moreover, when multiple drivers exist for the same RDBMS, the format for connection strings to the same database may be different.
According to the MySQL reference manual, MySQL uses the following format for its connection string:
MySQL (MM.MySQL Driver)
jdbc:mysql://<HOST>:<PORT>/<DB>
org.gjt.mm.mysql.Driver
Oracle thin client, on the other hand, uses this format:
Oracle Thin
jdbc:oracle:thin:#<HOST>:<PORT>:<SID>
oracle.jdbc.driver.OracleDriver
As you can see, slash / is part of the required syntax for MySql, but it is not part of the syntax for Oracle.

Windows Authentication for SQL Server using JBDC on a Mac

Is it possible to connect to SQL Server using Windows authentication/integrated security from a Mac? I am using the type 4 JDBC driver provided by Microsoft. The front end (a form application) is coded in Java. Everything works perfectly on Windows but one person in the office uses a Mac.
Is this possible? FYI, I have never used Macs so I am very much the novice with them. I have searched all over the Internet but have not found a solution.
Thank you in advance.
This information is hard to come by in my experience. All of my searches turned up wrong (outdated) information since Microsoft changed the rules and added the authenticationScheme parameter. In the interest of helping the next person, here is an example of a connection string that works:
jdbc:jtds:sqlserver://123.123.123;instance=server1;databaseName=students;integratedSecurity=true;authenticationScheme=JavaKerberos
Also in driver properties set "Domain". Do not include the domain in any user name setting.
This was tested using Squirrel SQL (Java) with jtds on Mac OSX. Hopefully the previous sentence has the search terms someone might use who needs to know this information.
Using Kerberos Integrated Authentication to Connect to SQL Server
Beginning in Microsoft JDBC Driver 4.0 for SQL Server, an application
can use the authenticationScheme connection property to indicate that
it wants to connect to a database using type 4 Kerberos integrated
authentication.
The jTDS JDBC driver for SQL Server supports Windows authentication simply using the domain property as described in the FAQ.
domain
Specifies the Windows domain to authenticate in. If present and the user name and
password are provided, jTDS uses Windows (NTLM)
authentication instead of the usual SQL Server authentication (i.e.
the user and password provided are the domain user and password). This
allows non-Windows clients to log in to servers which are only
configured to accept Windows authentication.
If the domain parameter is present but no user name and password are provided, jTDS uses its native Single-Sign-On library and logs in
with the logged Windows user's credentials (for this to work one would
obviously need to be on Windows, logged into a domain, and also have
the SSO library installed -- consult README.SSO in the distribution on
how to do this).
I use jTDS on a mac (10.9).
Using this driver you need to specify the username and password like always, the only difference is that you need to specify domain=WHATEVERTHENTDOMAIN in the connection string (or connection properties if you rather).
So a sample connection string is:
jdbc:jtds:sqlserver://db_server:1433/DB_NAME;domain=NT_DOMAIN_NAME
The jTDS driver then uses NTLM to login to the specified domain with the username and password.
This is an old post but may be relevant for some people. See this other SO post that describes how to connect to a SQL Server with Windows Authentication from a Linux machine through JDBC. This will work on mac as well.
jTDS is inferior to Microsoft's JDBC driver (in particular, it cannot figure out the types of parameters in a prepared statement)
Yes, you can authenticate to MS SQL Server using Active Directory authentication, as Active Directory is just Kerberos + LDAP, which are open source and implemented on Mac
Kerberos config /etc/krb5.conf :
[libdefaults]
default_realm = YOUR_REALM.NET
[realms]
YOUR_REALM.NET = {
kdc = host.your-domain.net
}
I needed to use the fully qualified domain name of the KDC, not just the domain name
JDBC Connection String:
jdbc:sqlserver://$host;database=$db;integratedSecurity=true;authenticationScheme=JavaKerberos
If $host does not have an SPN of MSSQLSrv/$host, add serverSp=$SPN to the JDBC connection string
It is not correct to say that one driver can determine the data types and another driver can't. Any driver has to look at the implied type based on the arguments passed. Both jTDS and Microsoft's driver do this. This is a limitation of the protocol - the database cannot tell the driver which type is correct, because in many queries it can't know what you intend.
In each version, jTDS and Microsoft's driver each have different issues and different advantages. The "best" choice depends on exactly which version of each you look at, and exactly what your needs are. I've had to switch back and forth as different versions come out - Microsoft breaking in a certain way, then later adding something I wanted.
The following connection string worked for me
jdbc:jtds:sqlserver://server_name:port_name;useLOBs=false;databaseName=db_name;useNTLMv2=true;domain=domain_name;
I'm using jTDS 1.3.2 and SQuirreL SQL Client.

Java ODBC and Microsoft.Jet.OLEDB.4.0

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/

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!

ODBC Connection Setup in 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);

Categories

Resources