Connect MSSQL using JDBC Java

Connect MSSQL using JDBC Java

In this sample java program you will see how to connect MSSql database using JDBC.

Please note: We are using jdbc-mssql.jar to connect MSSql database when you use this program please use this jar file in your classpath. We are going to include file for download as well in the bottom:

package com.javahonk;

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

public class MSSQLConnectionUsingJTDSDriver {
	
	public static void main(String[] args) {

		Connection connection = null;
		Statement stmt = null;
		String query = "select *  from Table";

		try {
			// Register JDBC Driver
			Class.forName("net.sourceforge.jtds.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:jtds:sqlserver://servername:portnumber","username", "password");

			stmt = connection.createStatement();
			ResultSet rs = stmt.executeQuery(query);
			while (rs.next()) {
				String accountNumber = rs.getString("accountNumber");
				System.out.println("Account Number: "+accountNumber);

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (connection != null) {
					connection.close();
				}
				if (stmt != null) {
					stmt.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}
}

Demo output:

Connect MSSQL using JDBC Java

Leave a Reply

Your email address will not be published. Required fields are marked *