In this tutorial we will learn JDBC connection with MySql database using MySqlConnector.jar. How to register MySql driver in java- How to getConnection in java - Writing your jdbc(Java database connectivity) program to connect with MySql. In previous tutorial we configures java build path in eclipse and connected with Oracle and MsSql databases.
Hostname = localHost,
Port =3306 (default port)
SID= mydb
Username =root
Password=MySql123
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"root", "MySql123");
|
Example/ Full program to connect to MySql database using Type 4 driver - java JDBC program >
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MySql_JdbcConnectionSetupExample {
public static void main(String... arg) {
Connection con = null;
try {
// registering Mysql driver class
Class.forName("com.mysql.jdbc.Driver");
// getting connection
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "root", "MySql123");
// Test connection is null or not
if (con != null)
System.out
.println("Connection established successfully with MySql database!");
else
System.out.println("No Connection!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (con != null)
con.close(); // close connection
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/*OUTPUT
Connection established successfully with MySql database!
*/
|
Above JDBC java program will connect you to MySql database using Type 4 java JDBC driver.
In this tutorial we learned JDBC connection with MySql database using MySqlConnector.jar. And registering MySql driver in java and getting MySql connection in java.
RELATED LINKS>