Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check sql database connection in java [closed]

Tags:

java

I am using sql server 2008. I need to check if I can establish connection using server name,port number,db name,user name and password.

Is there any simple method available?

like image 543
Anand B Avatar asked Oct 04 '12 10:10

Anand B


People also ask

What does con close () do?

connection. close(); is a normal JDBC connection method; it (usually) closes the associated objects and releases the connection; it's not uncommon to explicitly close statements and resultsets instead of depending on connection.

Does JDBC close connection?

Connection. close method, JDBC does not close the physical data source connection. Instead, JDBC closes only JDBC resources, such as Statement or ResultSet objects. The data source returns the physical connection to the connection pool for reuse.


1 Answers

Here is the sample JAVA program that checks whether the connection is successfully established to DB server or not.

public class TestDBConnection {

        public static void main(String[] args) {
            String Url = "jdbc:sqlserver://serverURL;DatabaseName=DBname;user=dbUsername;Password=dbPassword";
            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                System.out.println("Trying to connect");
                Connection connection = DriverManager.getConnection(Url);

                System.out.println("Connection Established Successfull and the DATABASE NAME IS:"
                        + connection.getMetaData().getDatabaseProductName());
            } catch (Exception e) {
System.out.println("Unable to make connection with DB");
                e.printStackTrace();
            }
        }
    }

Hope this will work for you.

like image 64
Arun Kumar Avatar answered Oct 10 '22 05:10

Arun Kumar