Friday, January 13, 2012

Java - mysql + java with netbeans - part 2

මෙන්න කලින් දවසේ post එකේ ඉතුරු ටික. මම හිතන්වා කට්ටියම mysql server එක install කරගෙන ඇති කියලා. එහෙම install කරලා නැති කට්ටිය WAMP හරි XAMPP හරි install කරගන්න.පහල තියන links වලින් ඒ දෙක download කරගනන් පුලුවන්.

WAMP
XAMPP

මම use කරන්නේ WAMP එක.install කරලා WAMP එක run කරගන්න. එතකොට පහල පිංතූරයේ තියනවා වගෙ notification area එකේ icon එකක් පෙන්නයි. ඒක උඩ click කරනකොට එන menu එකෙන් phpMyAdmin කියන එක select කරන්න.

එතකොට web browser එක හරහා phpMyAadmin open වෙනවා. එතන තියන create new database හරහා school කියලා database එකක් හදා ගන්න.

පහල තියනවා table එකට අදාල SQL code එක.

CREATE TABLE student (
  sid varchar(10) NOT NULL,
  fname varchar(30) NOT NULL,
  lname varchar(50) NOT NULL,
  dob date NOT NULL,
  address varchar(500) NOT NULL,
  tel varchar(10) DEFAULT NULL,
  PRIMARY KEY (sid)
);

දැන් netbeans open කරගෙන අපි කලින් හදාගත්ත project එක open කරගන්න. menubar එකේ windows යටතේ තියන services  යන එක click කරන්න.

services එකේ තියන database කියන එක උඩ right click කරලා new connection කියන එක කරන්න.
එන windows එකේ Driver යටතේ තියන drop down menu එකෙන් mysql කියන එක select කරන්න.

next button එක click කරලා එන  menu එකේ අදාල details fill කරන්න. JDBC URL එක අගට database එකේ නම type කරන්න.

එතකොට දැන් services කියන එකේ අලුතෙන් හදාගත්ත connection එක පෙන්නනවා


දැන් අපි බලමු netbeans හරහා කොහොමද table එකක් create කරගන්නේ කියලා.
services එකෙන් schhol/tables කියන එක උඩ right click කරලා create table කියන එක select කරන්න.
පහල පිංතූරේ තියන විදියට student table එක හදාගන්න.

ඔන්න දැන් අපි database එක සහ table එකක් හදාගෙන ඉවරයි.

දැන් අපි බලමු අපි කලින් හදාගත්ත DatabaseConnection class එක වැඩ කරනවාද කියලා.
ඒ සඳහා ඊයේ අපි හදාගත්ත class එකේ main method එකක් හදලා පහල තියන code එක ගහලා කරලා run බලන්න.

package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author Thusitha
 */
public class DatabaseConnection {
    public static Connection createConnection(String userName, String password, String datbaseName) throws SQLException {
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+datbaseName, userName, password);
        return connection;
    }
   
    public static void main(String[] args) {
        try {
            Connection myConncetion = createConnection("root", "123", "school");
            System.out.println(myConncetion.isClosed());
        } catch (SQLException ex) {
            Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

run කරන්න class එක උඩ right click කරලා run this file කියන එක select කරන්න.

run කලාම output එක විදියට false කියලා print වෙනවනම් අපේ method එක හරියට වැඩ කරනවා.


දැන්නම් හොඳ ගනං මේක type කරලා. ඉතුරු ටික ඊළඟ post එකෙන් බලාපොරොත්තු වන්න.

No comments:

Post a Comment