Java code for connecting MS SQL Server by using SQL Server Authentication

First of all, You will need to add a jar file to your project library as SQL Server 2000 Driver for JDBC Service. My target is SQL Server 2000, it will require the jar file called “sqljdbc4.jar”. This is not supported on Microsoft website now, you can download it here. For other versions of SQL Server, here is the link of SQL Server 2000 Driver for JDBC Service.

The following is the code for connection MS SQL Server and select some records from a testing table.

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class Main {
 
	public static void main(String[] args) throws SQLException, ClassNotFoundException {
		Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");	
		Connection conn = DriverManager.getConnection("jdbc:sqlserver://HOSP_SQL1.company.com;user=name;password=abcdefg;database=Test");
		System.out.println("test");
		Statement sta = conn.createStatement();
		String Sql = "select * from testing_table";
		ResultSet rs = sta.executeQuery(Sql);
		while (rs.next()) {
			System.out.println(rs.getString("txt_title"));
		}
	}
}

21 thoughts on “Java code for connecting MS SQL Server by using SQL Server Authentication”

  1. W3Schools Demo
    Resize this responsive page!

    London
    London is the capital city of England.
    It is the most populous city in the United Kingdom,
    with a metropolitan area of over 13 million inhabitants.

    Paris
    Paris is the capital and most populous city of France.

    Tokyo
    Tokyo is the capital of Japan, the center of the Greater Tokyo Area,
    and the most populous metropolitan area in the world.

  2. try {
    Class.forName(“com.mysql.jdbc.Driver”);
    connection = DriverManager.getConnection(
    “jdbc:mysql://HOST:port_number/DB_name”,”DB_username”, “DB_pass”);
    st = connection.createStatement();
    rs = st.executeQuery(“SELECT * FROM table name WHERE id = 1”);
    } catch (Exception e) {
    System.out.println(“DB error : ” + e);
    }

Leave a Comment