I am new to JDBC and I am trying to make a connection to a MySQL database.
I am using Connector/J driver, but I cant find the JDBC connection string for my Class.forName() method.
host:port is the host name and port number of the computer hosting your database. If not specified, the default values of host and port are 127.0.0.1 and 3306, respectively.
database is the name of the database to connect to. If not specified, a connection is made with no default database.
failover is the name of a standby database (MySQL Connector/J supports failover).
propertyName=propertyValue represents an optional, ampersand-separated list of properties. These attributes enable you to instruct MySQL Connector/J to perform various tasks.
Go to MySQL workbench and lookup for Database > Manage Connections
you will see a list of connections. Click on the connection you wish to connect to.
You will see a tabs around connection, remote management, system profile. Click on connection tab.
your url is jdbc:mysql://<hostname>:<port>/<dbname>?prop1 etc.
where <hostname> and <port> are given in the connection tab.It will mostly be localhost : 3306. <dbname> will be found under System Profile tab in Windows Service Name. Default will mostly be MySQL5<x> where x is the version number eg. 56 for MySQL5.6 and 55 for MySQL5.5 etc.You can specify ur own Windows Service name to connect too.
Construct the url accordingly and set the url to connect.
If you are using Java 7 then there is no need to even add the Class.forName("com.mysql.jdbc.Driver").newInstance (); statement.Automatic Resource Management (ARM) is added in JDBC 4.1 which comes by default in Java 7.
The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets ([ ]) being optional:
As the answer seems already been answered, there is not much to add but I would like to add one thing to the existing answers.
This was the way of loading class for JDBC driver for mysql
com.mysql.jdbc.Driver
But this is deprecated now. The new driver class is now
com.mysql.cj.jdbc.Driver
Also the driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
The method Class.forName() is used to register the JDBC driver. A connection string is used to retrieve the connection to the database.
The way to retrieve the connection to the database is shown below. Ideally since you do not want to create multiple connections to the database, limit the connections to one and re-use the same connection. Therefore use the singleton pattern here when handling connections to the database.
Shown Below shows a connection string with the retrieval of the connection: