How to Connect Java to MySQL
After we learn how to connecting Java Program to Microsoft SQL Server, now we learn to connecting our java program to MySQL.
So we must prepare tools for that, and the tools is:
1. NetBeans IDE 7.0, you can download here.
2. MySQL 5.0 , and you can download here.
3. JDBC Driver for MySQL, you can download on this site. Add this driver to our Java Project library that we will make it.
First, we must create project Java on NetBeans IDE, for the example ConnectMySQL.
And then create packages by right click on Source Packages and choose New -> Java Packages and create name on that packages for the example same with the Project Name Connect MySQL.
And then create packages by right click on Source Packages and choose New -> Java Packages and create name on that packages for the example same with the Project Name Connect MySQL.
After that, create one class by right click on our new packages , and choose New -> Java Class and create our New Java Class with MySQLConnection.java and type or copy paste this code on our new Java Class.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
class MySQLConnection{
Connection Connect;
public Connection ConnectDB(){
String url = "jdbc:mysql://localhost/test";
try{
Class.forName("com.mysql.jdbc.Driver");
Connect = DriverManager.getConnection(url, "root", "root");
}catch(ClassNotFoundException e){
System.out.println("Driver Load Failed!");
}catch(SQLException e){
System.out.println("Connection Failed!");
}
return Connect;
}
public static void main(String[] abc){
Connection Con = new MySQLConnection().ConnectDB();
if(Con != null){
System.out.println("Connection Succesfull!");
}else{
System.out.println("Connection Failed!");
}
}
}
If you have finished, then we must create New Java Form by right click on MySQLServer packages and then choose New -> JFrame Form. And create one button and name on it with "Test Connection MySQL". And then copy paste this code to our new button.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = new MySQLConnection().ConnectDB();
try{
if(con != null){
JOptionPane.showMessageDialog(null, "Connection Succesfull!");
}else{
JOptionPane.showMessageDialog(null, "Connection Failed!");
}
}catch(Exception e){
}
}
and do the same thing like our Java to SQL Server project.
0 Comments:
Post a Comment
<< Home