get Connection to sqlserver Database - Java java.sql

Java examples for java.sql:SqlServer

Description

get Connection to sqlserver Database

Demo Code


//package com.java2s;
import java.sql.Connection;
import java.sql.DriverManager;

import java.sql.SQLException;

public class Main {

    private static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

    private static String url = "jdbc:jtds:sqlserver://192.168.81.16:55944;databaseName=ATDataBase";

    private static String user = "uapp_autotest";

    private static String password = "1qaz@wsx";

    public static Connection getConnection() {
        try {/* w w w .ja  va  2  s. com*/
            Class.forName(driver);
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static Connection getConnection(String connecturl,
            String username, String psw) {
        url = connecturl;
        user = username;
        password = psw;
        return getConnection();
    }

    public static Connection getConnection(String connecturl) {
        url = connecturl;
        user = "";
        password = "";
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        try {
            return DriverManager.getConnection(url);
        } catch (SQLException ex) {
            ex.printStackTrace();
            return null;
        }
    }
}

Related Tutorials