Connect Java To MySQL Using DataSource

How To Connect Java To MySQL Database Using DataSource In NetBeans

Connect Java To MySQL Database



In this Java Tutorial we will see How To Create a Connection Between Java NetBeans and MySQL Database Using Datasource And Display Data From Database .



WATCH THIS JAVA TUTORIAL

downloads connector:  http://dev.mysql.com/downloads/connector/j

Project Source Code:

// package to import
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

// make sure to add a jar connector to your project ( watch the video )
    // create a connection with mysql
    public Connection createConnection(String serverName, Integer portNumber, String userName, String password, String dbName){
        
        
        Connection myConnection = null;
        
// create a datasource 
        MysqlDataSource datasource = new MysqlDataSource();
        
        datasource.setServerName(serverName);
        datasource.setPortNumber(portNumber);
        datasource.setUser(userName);
        datasource.setPassword(password);
        datasource.setDatabaseName(dbName);
        
        try {
            myConnection = datasource.getConnection();
        } catch (SQLException ex) {
            Logger.getLogger(Connect_To_MySQL.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return myConnection;
    }


// button to display data from mysql database
    private void jButton_Display_ActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        
        Connection connection = createConnection("localhost", 3306, "root", "", "student_db");
        
        Statement st;
        ResultSet rs;
        
        try {
            
            st = connection.createStatement();
            rs = st.executeQuery("SELECT * FROM `course`");
            
            while(rs.next()){
                System.out.println(rs.getString("label"));
            }
            rs.close();
            st.close();
        } catch (SQLException ex) {
            Logger.getLogger(Connect_To_MySQL.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }                                                

OutPut:

connect java to mysql database using datasource in netbeans





Share this

Related Posts

Previous
Next Post »