To connect with MySql database with JDBC driver follow the same basic steps discussed in previous tutorials. We have to know the following information to connect with MySql database:
1. Driver class: com.mysql.jdbc.Driver.
2. Connection URL:
Syntax:
"jdbc:mysql://hostname:port/dbname","username", "password"
Connection url for MySql database: jdbc:mysql://localhost:3306/w3schools
where 3306 is the port number and w3schools is the database name.
3. Username: Username of MySql database, default is root.
4. Password: Password of MySql database.
Example:
JDBCMySqlTest.java
import java.sql.Connection; import java.sql.DriverManager; /** * This class is used to create a JDBC * connection with MySql DB. * @author w3schools */ public class JDBCOracleTest { //JDBC and database properties. private static final String DB_DRIVER = "com.mysql.jdbc.Driver"; private static final String DB_URL = "jdbc:mysql://localhost:3306/w3schools"; private static final String DB_USERNAME = "root"; private static final String DB_PASSWORD = "root"; public static void main(String args[]){ Connection conn = null; try{ //Register the JDBC driver Class.forName(DB_DRIVER); //Open the connection conn = DriverManager. getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); if(conn != null){ System.out.println("Successfully connected."); }else{ System.out.println("Failed to connect."); } }catch(Exception e){ e.printStackTrace(); } } } |
Output:
Successfully connected. |
Download this example.
Next Topic: JDBC Statement interface.
Previous Topic: Connect to Oracle database with JDBC driver.