CodesJava

Easy learning with example program codes

Connect to MySql database with JDBC driver


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/javawithease

where 3306 is the port number and javawithease 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 javawithease
 */
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/javawithease";
	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.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.

 

Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki