# Get `Connector/J` Connection Object: Example
__*DriverManager.getConnection*__
+ use **`DriverManager.getConnection()`**  
```
import ~!@java.sql.Connection@!~;
import ~!@java.sql.DriverManager@!~;
public class DemoJdbcConnection{
    public static void main(String[] args){
        Connection connection = null;
        try{
            // Connect to TiDB server instance directly
            connection = ~!@DriverManager.getConnection@!~(
                "jdbc:mysql://localhost:4000/~!@test@!~", "root", ""
            );
            System.out.println("Connection established");
        }
        catch(Exception e){
            System.out.println("Error: "+e.toString());
        }
        finally{
           ...
        }
    }
}
```

------------------------------------------------------------
Firstly, we import DriverManager in java.sql. 

Many operations in Java do not return values to indicate success or failure, but rely on exceptions with try/catch blocks.

Obtain a Connection instance to your database by calling DriverManager.getConnection(). 

The DriverManager's getConnection() method accepts three parameters:

A URL that describes the driver to use, the server host, and the default database (if required)

The TiDB username

The TiDB password

The URL begins with the protocol designator, jdbc, and then the subprotocol designator, which represents the name of the database driver, mysql. The protocol and subprotocol designators are mandatory. 

Other parts of the URL are optional. If you omit the host and port name, the default value is localhost:3306. You can omit the default database if you do not want to specify a default database upon connection.

An alternative syntax for specifying the user and password is to add them as parameters to the end of the connection URL:jdbc:mysql://myserverhost/testdb?user=testuser&password=testpass

With this approach, getConnection() requires only one argument.


For example, on the slide, we connect to the TiDB database on localhost with port number 4000, and open the database test as the default database.

If you are connecting to TiDB from within an application server, the method you use depends on the application server.

```
import java.sql.Connection;
import java.sql.DriverManager;
public class DemoJdbcConnection{
    public static void main(String[] args){
        Connection connection = null;
        try{
            // Connect to TiDB server instance directly
            connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:4000/test", "root", ""
            );
            System.out.println("Connection established");
        }
        catch(Exception e){
            System.out.println("Error: "+e.toString());
        }
        finally{
           ...
        }
    }
}
```
