In this tutorial you will learn how to get connection to a MySQL database.
In this tutorial you will learn how to get connection to a MySQL database.To connect java application to the database we do the following fundamental steps
1. Load the driver of particular database you are using.
2. Create a Connection object to get a connection.
3. Create a statement object to for executing query.
4. Create a Resultset object to store the query.
5. Finally close the Connection, Statement and Resultset objects.
At first create table named student in MySQL database inset values into it as.
Creating A table
CREATE TABLE `student` (
`rollno` int(11) NOT NULL,
`name` varchar(50) default NULL,
`course` varchar(20) default NULL,
PRIMARY KEY (`rollno`)
)
Inserting Values
INSERT INTO STUDENT(rollno,name,course) VALUES(1,'John',B.Tech') ;
A Simple example is given below to connect a java application to MySQL database
MySQLConnect.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQLConnect {
public static void main(String[] args) throws SQLException {
System.out.println("MySQL Connect Example.");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
// 3306 is the default port number of MySQL
String url = "jdbc:mysql://localhost/";
String dbName = "student";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
// Load the driver
Class.forName(driver);
// Get a connection
conn = DriverManager
.getConnection(url + dbName, userName, password);
System.out.println("Connected to the database");
// Create a Statement
stmt = conn.createStatement();
// Create a query String
String query = "SELECT * FROM student";
rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println("Roll No- " + rs.getInt("rollno")
+ ", Student Name- " + rs.getString("name")
+ ", Student Course " + rs.getString("course"));
}
} catch (ClassNotFoundException e) {
System.out.println("Class Not found Exception cought");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Closing the connection
conn.close();
stmt.close();
rs.close();
System.out.println("Disconnected from database");
}
}
}
| Connected to the database Roll No- 1, Student Name- John, Student Course B.Tech Disconnected from database |