connect()

Method that returns a new database connection object.

connect(url, user, password)

This method returns a new database Connection object after connecting to the given URL and authenticating the connection with the provided user and password information.
The function accepts arguments as described here: https://docs.oracle.com/javase/8/docs/api/java/sql/DriverManager.html#getConnection-java.lang.String-java.lang.String-java.lang.String-.
In the returned Connection object normally any public method should be available. The returned Connection object is described here: https://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html.

Note: Make sure to close any Connection object created by connect() and any other closable resources created from the Connection instance (ResultSet, etc.).

url

String that represents a database url of the form jdbc:subprotocol:subname, e.g. 'jdbc:mysql://localhost:3306/mycompany'.
The syntax will be specific to the database, or more precisely the JDBC connector. Currently Datamapper supports the following JDBC connectors:

  • com.mysql.cj.jdbc.Driver

  • sun.jdbc.odbc.JdbcOdbcDriver

  • com.microsoft.sqlserver.jdbc.SQLServerDriver

  • oracle.jdbc.OracleDriver

For older databases that only have an ODBC driver, a JDBC-ODBC bridge can be called using the jdbc:olodbc prefix.
The syntax is: db.connect("jdbc:olodbc:...", ..., ...);

Note that the JDBC-ODBC bridge can only execute a SELECT request; no write actions are allowed. For supported objects and methods of the returned Connection object, see JDBC-ODBC bridge: objects and methods.

This bridge replaces the legacy bridge which was deprecated. The legacy bridge can still be selected with jdbc:odbc:, and its functionality remains unchanged.

user

String that represents the name of the database user on whose behalf the connection is being made. This is used for authentication.

password

String that represents the user's password. This is used for authentication.

Example

Here's an example of how to connect to a mySQL database and retrieve a data value.

Copy
con = db.connect('jdbc:mysql://localhost:3306/mycompany','root','admin');
statement = con.createStatement();
values = statement.executeQuery("select * from datavalue");
if (values.next())    
    values.getString("data");
else    
    'nothing';
values.close();
statement.close();
con.close();