Friday, April 8, 2011

Database Connection in java and create database in java

There are many process to connect database in java.
First of all you have to download the connector for java from mysql web.
From mysql website:
Mysql Connector
From Amadernetwork.22web.net
Mysql Connector
For netbeans you can add mysql connector from  library .
Or if you use jcreator or other editor extract the jar file and copy the com folder and paste it into
your current directory.

A simple code for connect mysql in java:

import java.sql.*;
import java.sql.ResultSet;
import javax.swing.*;

public class mysqltest
{
    
    
    
    public static void main (String[] args) {
        
    Connection connection;
    Statement statement;
    ResultSet resultSet ;
    ResultSetMetaData metaData;
    String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    String DATABASE_URL = "jdbc:mysql://localhost/mysql";
    //JOptionPane.showMessageDialog(null,"adsas");
    try{
    Class.forName( JDBC_DRIVER );
        connection =DriverManager.getConnection( DATABASE_URL, "root", "" );
            statement =connection.createStatement();
            
            statement.executeUpdate("CREATE DATABASE if not exists `testing`");
            JOptionPane.showMessageDialog(null,"Created");
    }
    catch(Exception e)
    {
         JOptionPane.showMessageDialog(null,e.toString());
    }
        
}
}

This code will connect with mysql and Create a database.
Download this source code.
http://amadernetwork.22web.net/java101.zip 

All database oeration will published soon. 

No comments:

Post a Comment