Java වල Database Connect කරමු - JDBC MySQL Oracle SC Guide

Java වල Database Connect කරමු - JDBC MySQL Oracle SC Guide

ආයුබෝවන්, මගේ යාළුවනේ! කොහොමද ඉතින්? අද අපේ Ghost බ්ලොග් එකෙන් කතා කරන්න යන්නේ ගොඩක්ම වැදගත්, හැම Java Developers කෙනෙක්ටම නැතුවම බැරි දෙයක් ගැන. ඒ තමයි Java වලින් Database එකකට connect වෙන හැටි. විශේෂයෙන්ම අපි අද බලමු MySQL සහ Oracle database වලට JDBC (Java Database Connectivity) හරහා DriverManager එක පාවිච්චි කරලා connect වෙන්නේ කොහොමද කියලා.

ඔයාලා දන්නවනේ, මොන software එකක් හැදුවත්, data නැතුව වැඩක් නෑනේ. Data save කරන්න, edit කරන්න, delete කරන්න අපිට database එකක් ඕනේම වෙනවා. ඉතින් Java application එකකට database එකක් එක්ක කතා කරන්න පුළුවන් වුණොත්, අපේ application එකේ හැකියාවන් සිරාවටම වැඩි වෙනවා. මේක නම් ෆට්ට වැඩක්! එහෙනම්, වැඩි කතා නැතුව අපි වැඩේට බහිමු.

JDBC කියන්නේ මොකක්ද?

සරලවම කිව්වොත්, JDBC කියන්නේ Java application එකකට database එකක් එක්ක කතා කරන්න පුළුවන් කරන API (Application Programming Interface) එකක්. මේක අපිට database එකකට connect වෙන්න, SQL queries execute කරන්න, data retrieve කරන්න වගේ ගොඩක් දේවල් කරන්න උදව් වෙනවා. JDBC හරහා අපිට ඕනෑම relational database එකක් (MySQL, Oracle, PostgreSQL, SQL Server වගේ) එක්ක වැඩ කරන්න පුළුවන්. ඒකට හේතුව තමයි JDBC එක database-independent විදියට design කරලා තියෙන නිසා.

අපිට විවිධ databases වලට connect වෙන්න පුළුවන් වෙන්නේ ඒ database එකට අදාළ JDBC Driver එකක් තියෙන නිසයි. මේ Drivers තමයි Java calls ටික database එකට තේරෙන භාෂාවට (database specific protocol) translate කරන්නේ.

අවශ්‍ය කරන දේවල් සෙට් කරගමු

මේ වැඩේට බහින්න කලින් අපිට පොඩි පොඩි දේවල් ටිකක් සෙට් කරගන්න වෙනවා. කලබල වෙන්න එපා, මේවා නම් ලේසි වැඩ!

  1. Java Development Kit (JDK): අනිවාර්යයෙන්ම ඕනේ. ඔයාලගේ computer එකේ JDK එක install කරලා නැත්නම්, මුලින්ම ඒක install කරගන්න. Java code compile කරන්නයි, run කරන්නයි අපිට JDK එක ඕනේ.
  2. Database Server: ඔයාට MySQL ද, Oracle ද කියන එක තෝරගන්න වෙනවා.Database එකක් install කරලා, ඒකේ database එකක් (e.g., mydatabase) සහ user කෙනෙක් (e.g., myuser) හදාගන්න.
    • MySQL: MySQL Community Server එක install කරගන්න පුළුවන්. WAMP, XAMPP වගේ packages වලත් MySQL තියෙනවා.
    • Oracle: Oracle Database Express Edition (XE) එක personal use එකට හොඳටම ඇති.
  3. JDBC Driver JAR File: මේක තමයි අපේ Java application එකයි database එකයි අතර පාලම.මේ JAR file එක ඔයාගේ project එකේ classpath එකට add කරන්න අමතක කරන්න එපා. Maven, Gradle වගේ build tools පාවිච්චි කරනවා නම් dependencies විදියට add කරන්න පුළුවන්. Simple project එකක් නම්, project folder එකේ lib කියන folder එකක් හදලා ඒකට දාලා, IDE එකේ Build Path එකට add කරන්න.
    • MySQL: mysql-connector-java.jar file එක download කරගන්න වෙනවා. (Google "MySQL JDBC driver download")
    • Oracle: ojdbcX.jar file එක download කරගන්න වෙනවා. (X කියන්නේ version එක, e.g., ojdbc8.jar). (Google "Oracle JDBC driver download")
  4. An IDE (Integrated Development Environment): Eclipse, IntelliJ IDEA, NetBeans වගේ එකක් පාවිච්චි කරන එක ලේසියි.

MySQL Database එකකට සම්බන්ධ වෙමු

හරි, දැන් අපි බලමු කොහොමද MySQL database එකකට JDBC DriverManager එක පාවිච්චි කරලා connect වෙන්නේ කියලා. මේක නම් හරිම සරලයි.

මූලික පියවර ටික මෙහෙමයි:

Resources Close කිරීම:වැඩේ ඉවර වුණාට පස්සේ Connection, Statement, ResultSet objects ටික close කරන්න අමතක කරන්න එපා. මේක ගොඩක්ම වැදගත් resource leaks වළක්වා ගන්න.


            rs.close();
            stmt.close();
            con.close();
        

Results Process කිරීම:ResultSet එකෙන් data ටික extract කරගන්න පුළුවන්. rs.next() කියන method එකෙන් අපි එකින් එක record වලට යනවා.


            while (rs.next()) {
                System.out.println(rs.getInt(1) + "  " + rs.getString(2) + "  " + rs.getString(3));
            }
        

Query එකක් Execute කිරීම:SQL query එකක් run කරන්න stmt.executeQuery() (SELECT queries වලට) හෝ stmt.executeUpdate() (INSERT, UPDATE, DELETE queries වලට) පාවිච්චි කරනවා.


            ResultSet rs = stmt.executeQuery("SELECT * FROM your_table_name");
        

Statement එකක් හදාගැනීම:දැන් අපිට SQL queries execute කරන්න Statement object එකක් ඕනේ. ඒක Connection object එකෙන් හදාගන්න පුලුවන්.


            Statement stmt = con.createStatement();
        

Connection එකක් හදාගැනීම:ඊළඟට අපි DriverManager.getConnection() method එක පාවිච්චි කරලා database එකට connection එකක් හදාගන්නවා. මේකට parameters තුනක් දෙන්න ඕනේ: database URL එක, username එක, password එක.


            String url = "jdbc:mysql://localhost:3306/your_database_name";
            String user = "your_username";
            String password = "your_password";
            Connection con = DriverManager.getConnection(url, user, password);
        

your_database_name, your_username, your_password කියන තැන් වලට ඔයාගේ database details හරියටම දෙන්න ඕනේ.

JDBC Driver එක Load කිරීම:මුලින්ම අපි Driver class එක memory එකට load කරගන්න ඕනේ. ඒකට Class.forName() method එක පාවිච්චි කරනවා.


            Class.forName("com.mysql.cj.jdbc.Driver");
        

com.mysql.cj.jdbc.Driver කියන්නේ MySQL වල නවතම Driver class එක. ඔයා පරණ version එකක් පාවිච්චි කරනවා නම් com.mysql.jdbc.Driver වෙන්න පුළුවන්.

සම්පූර්ණ MySQL Connection උදාහරණය:


import java.sql.*;

public class MySQLConnector {
    public static void main(String args[]) {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // Step 1: Load the JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("MySQL JDBC Driver Registered!");

            // Step 2: Establish the connection
            String url = "jdbc:mysql://localhost:3306/your_database_name?useSSL=false&allowPublicKeyRetrieval=true"; // Add SSL/PublicKey settings if needed
            String user = "your_username";
            String password = "your_password";
            
            con = DriverManager.getConnection(url, user, password);
            System.out.println("Connection established to MySQL Database!");

            // Step 3: Create a Statement object
            stmt = con.createStatement();

            // Step 4: Execute a query
            rs = stmt.executeQuery("SELECT id, name, email FROM users"); // Replace 'users' with your table name
            System.out.println("\n--- User Data ---");

            // Step 5: Process the results
            while (rs.next()) {
                System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name") + ", Email: " + rs.getString("email"));
            }

        } catch (ClassNotFoundException e) {
            System.out.println("MySQL JDBC Driver not found!");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
        } finally {
            // Step 6: Close resources
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (con != null) con.close();
                System.out.println("Resources closed.");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Oracle Database එකකට සම්බන්ධ වෙමු

MySQL වලට connect වුණා වගේම Oracle database එකකටත් connect වෙන්න පුළුවන්. පියවර ටික පොඩ්ඩක් වෙනස් වෙනවා Driver class එකයි URL එකයි විතරයි.

මූලික පියවර ටික මෙහෙමයි:

  1. ඉතුරු පියවර:Statement හදාගැනීම, Query execute කිරීම, Results process කිරීම, සහ Resources close කිරීම MySQL වලට කරපු විදියටම කරන්න පුළුවන්.

Connection එකක් හදාගැනීම:


            // For SID
            // String url = "jdbc:oracle:thin:@localhost:1521:your_sid";
            // For Service Name
            String url = "jdbc:oracle:thin:@//localhost:1521/your_service_name";
            String user = "your_username";
            String password = "your_password";
            Connection con = DriverManager.getConnection(url, user, password);
        

Oracle වල URL එක MySQL වලට වඩා පොඩ්ඩක් වෙනස්. ඔයා SID (System ID) එකක් පාවිච්චි කරනවා නම් පළවෙනි format එක, Service Name එකක් පාවිච්චි කරනවා නම් දෙවෙනි format එක පාවිච්චි කරන්න.

JDBC Driver එක Load කිරීම:


            Class.forName("oracle.jdbc.driver.OracleDriver");
        

Oracle Driver class එක oracle.jdbc.driver.OracleDriver තමයි.

සම්පූර්ණ Oracle Connection උදාහරණය:


import java.sql.*;

public class OracleConnector {
    public static void main(String args[]) {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // Step 1: Load the JDBC driver
            Class.forName("oracle.jdbc.driver.OracleDriver");
            System.out.println("Oracle JDBC Driver Registered!");

            // Step 2: Establish the connection
            // Use SID if applicable: jdbc:oracle:thin:@localhost:1521:your_sid
            // Use Service Name:
            String url = "jdbc:oracle:thin:@//localhost:1521/your_service_name"; // e.g., XE, ORCLPDB1
            String user = "your_username"; // e.g., HR, C##MYUSER
            String password = "your_password";
            
            con = DriverManager.getConnection(url, user, password);
            System.out.println("Connection established to Oracle Database!");

            // Step 3: Create a Statement object
            stmt = con.createStatement();

            // Step 4: Execute a query
            rs = stmt.executeQuery("SELECT employee_id, first_name, last_name FROM employees"); // Replace 'employees' with your table
            System.out.println("\n--- Employee Data ---");

            // Step 5: Process the results
            while (rs.next()) {
                System.out.println("ID: " + rs.getInt("employee_id") + ", Name: " + rs.getString("first_name") + " " + rs.getString("last_name"));
            }

        } catch (ClassNotFoundException e) {
            System.out.println("Oracle JDBC Driver not found!");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
        } finally {
            // Step 6: Close resources
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (con != null) con.close();
                System.out.println("Resources closed.");
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

වැදගත් උපදෙස් සහ හොඳම භාවිතයන්

මේ වැඩේ කරද්දී පොඩි පොඩි දේවල් ටිකක් ගැන සැලකිලිමත් වුණොත් ඔයාලගේ ජීවිතේ ගොඩක් ලේසි වෙයි.

  • try-catch-finally බ්ලොක් එක අනිවාර්යයි: Database operations වලදී errors එන්න තියෙන ඉඩකඩ වැඩියි. ඒ නිසා හැමවිටම try-catch-finally බ්ලොක් එකක් ඇතුළේ code එක ලියන්න. finally බ්ලොක් එකේදී resources (Connection, Statement, ResultSet) close කරන්න අමතක කරන්න එපා. නැත්නම් resource leaks වෙලා application එකේ performance අඩු වෙන්න පුළුවන්.
  • JDBC Drivers: ඔයා පාවිච්චි කරන database version එකට ගැලපෙන JDBC driver එක පාවිච්චි කරන්න. සමහර වෙලාවට driver version එකයි database version එකයි අතර නොගැලපීම් නිසා errors එන්න පුළුවන්.
  • Security: Production applications වලදී username, password වගේ sensitive data code එකේ කෙලින්ම hardcode කරන්න එපා. ඒ වෙනුවට environment variables, configuration files, හෝ secure key vaults පාවිච්චි කරන්න.
  • PreparedStatement: මේ tutorial එකේ අපි Statement පාවිච්චි කළාට, real-world applications වලදී PreparedStatement පාවිච්චි කරන එක ගොඩක් හොඳයි. ඒක SQL Injection attacks වලින් ආරක්ෂා වෙන්නයි, performance වැඩි කරගන්නයි උදව් වෙනවා.
  • Connection Pooling: High-traffic applications වලදී හැම request එකකටම අලුතෙන් connection එකක් හදන එක ගොඩක් resource-intensive වැඩක්. ඒ වගේ වෙලාවට Connection Pooling libraries (e.g., HikariCP, C3P0, Apache DBCP) පාවිච්චි කරන එක වඩාත් කාර්යක්ෂමයි.

නිගමනය

ඉතින්, මචංලා, දැක්කනේ Java application එකකින් database එකකට connect වෙන එක එච්චර අමාරු වැඩක් නෙවෙයි කියලා. JDBC DriverManager පාවිච්චි කරලා MySQL සහ Oracle database වලට connect වෙන හැටි, data ටික extract කරගන්න හැටි, වැදගත් tips වගේ දේවල් ගොඩක් අද අපි කතා කළා.

මේක ඔයාලට Java database programming වලට හොඳ ආරම්භයක් වෙයි කියලා මම හිතනවා. මේවා නිකන් කියවලා වැඩක් නෑ. ඔයාලත් මේ උදාහරණ ටික ඔයාලගේ IDE එකේ run කරලා බලන්න. පොඩි පොඩි වෙනස්කම් කරලා, tables හදලා, data insert කරලා experiment කරන්න. එතකොට තමයි හරියටම දේ තේරෙන්නේ.

ඔයාලට මොකක් හරි ගැටලුවක් ආවොත්, නැත්නම් මේ ගැන තවත් දැනගන්න ඕනේ නම්, පල්ලෙහා comment section එකේ අනිවාර්යයෙන්ම comment එකක් දාන්න. අපි උදව් කරන්න ලෑස්තියි. මේ ලිපිය ඔයාලගේ යාළුවොත් එක්ක share කරන්නත් අමතක කරන්න එපා. එහෙනම්, තවත් අලුත් ලිපියකින් හමුවෙමු! Happy Coding!