How do I connect to a SQL Server 2008 database using JDBC?

JavaSql ServerSql Server-2008Jdbc

Java Problem Overview


I have MSSQL 2008 installed on my local PC, and my Java application needs to connect to a MSSQL database. I am a new to MSSQL and I would like get some help on creating user login for my Java application and getting connection via JDBC. So far I tried to create a user login for my app and used following connection string, but I doesn't work at all. Any help and hint will be appreciated.

jdbc:jtds:sqlserver://127.0.0.1:1433/dotcms 
username="shuxer"  password="itarator"

Java Solutions


Solution 1 - Java

There are mainly two ways to use JDBC - using Windows authentication and SQL authentication. SQL authentication is probably the easiest. What you can do is something like:

String userName = "username";
String password = "password";

String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB";

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);

after adding sqljdbc4.jar to the build path.

For Window authentication you can do something like:

String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);

and then add the path to sqljdbc_auth.dll as a VM argument (still need sqljdbc4.jar in the build path).

Please take a look here for a short step-by-step guide showing how to connect to SQL Server from Java using jTDS and JDBC should you need more details. Hope it helps!

Solution 2 - Java

You can use this :

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
 
public class ConnectMSSQLServer
{
   public void dbConnect(String db_connect_string,
            String db_userid,
            String db_password)
   {
      try {
         Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
         Connection conn = DriverManager.getConnection(db_connect_string,
                  db_userid, db_password);
         System.out.println("connected");
         Statement statement = conn.createStatement();
         String queryString = "select * from sysobjects where type='u'";
         ResultSet rs = statement.executeQuery(queryString);
         while (rs.next()) {
            System.out.println(rs.getString(1));
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
 
   public static void main(String[] args)
   {
      ConnectMSSQLServer connServer = new ConnectMSSQLServer();
      connServer.dbConnect("jdbc:sqlserver://<hostname>", "<user>",
               "<password>");
   }
}

Solution 3 - Java

I am also using mssql server 2008 and jtds.In my case I am using the following connect string and it works.

Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
Connection con = DriverManager.getConnection( "jdbc:jtds:sqlserver://<your server ip     
address>:1433/zacmpf", userName, password );
Statement stmt = con.createStatement();
       

Solution 4 - Java

If your having trouble connecting, most likely the problem is that you haven't yet enabled the TCP/IP listener on port 1433. A quick "netstat -an" command will tell you if its listening. By default, SQL server doesn't enable this after installation.

Also, you need to set a password on the "sa" account and also ENABLE the "sa" account (if you plan to use that account to connect with).

Obviously, this also means you need to enable "mixed mode authentication" on your MSSQL node.

Solution 5 - Java

Try to use like this: jdbc:jtds:sqlserver://127.0.0.1/dotcms; instance=instanceName

I don't know which version of mssql you are using, if it is express edition, default instance is sqlexpress

Do not forget check if SQL Server Browser service is running.

Solution 6 - Java

You can try configure SQL server:

  1. Step 1: Open SQL server 20xx Configuration Manager
  2. Step 2: Click Protocols for SQL.. in SQL server configuration. Then, right click TCP/IP, choose Properties
  3. Step 3: Click tab IP Address, Edit All TCP. Port is 1433

NOTE: ALL TCP port is 1433 Finally, restart the server.

Solution 7 - Java

Simple Java Program which connects to the SQL Server.

NOTE: You need to add sqljdbc.jar into the build path

// localhost : local computer acts as a server

// 1433 : SQL default port number

// username : sa

// password: use password, which is used at the time of installing SQL server management studio, In my case, it is 'root'

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

    public class Conn {
    	public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    
    		Connection conn=null;
    		try {
    			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
    			conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=company", "sa", "root");
    
    			if(conn!=null)
    				System.out.println("Database Successfully connected");
    
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    
    	}
    }

Solution 8 - Java

> Try this. > > import java.sql.Connection; > > import java.sql.DriverManager; > > import java.sql.ResultSet; > > import java.sql.Statement; > > > public class SQLUtil { > > public void dbConnect(String db_connect_string,String db_userid, > String db_password) { >
try { > > Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); > Connection conn = DriverManager.getConnection(db_connect_string, > db_userid, db_password); > System.out.println("connected"); > Statement statement = conn.createStatement(); > String queryString = "select * from cpl"; > ResultSet rs = statement.executeQuery(queryString); > while (rs.next()) { > System.out.println(rs.getString(1)); > } > } catch (Exception e) { > e.printStackTrace(); > } } > > public static void main(String[] args) { >
SQLUtil connServer = new SQLUtil(); >
connServer.dbConnect("jdbc:sqlserver://192.168.10.97:1433;databaseName=myDB", > "sa", > "0123");
> } > }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontarasView Question on Stackoverflow
Solution 1 - JavaThusiView Answer on Stackoverflow
Solution 2 - JavaMahmut EFEView Answer on Stackoverflow
Solution 3 - JavaktaView Answer on Stackoverflow
Solution 4 - JavadjangofanView Answer on Stackoverflow
Solution 5 - Javauser301201View Answer on Stackoverflow
Solution 6 - JavaRicky Nguyen Anh GiauView Answer on Stackoverflow
Solution 7 - Javak_kumarView Answer on Stackoverflow
Solution 8 - JavaKamranView Answer on Stackoverflow