Thursday, April 17, 2008

Integrating JavaDB with Netbeans modules - Series 3

In this last part of the series, I will show how to save and retrieve data from our embedded database.

  1. Create a new class called DBConect under the package org.embedded.db. Replace with the following code:
    1. package org.embedded.db;
    2. import java.sql.Connection;
    3. import java.sql.DriverManager;
    4. import java.sql.ResultSet;
    5. import java.sql.SQLException;
    6. import java.sql.Statement;
    7. import java.util.Properties;
    8. import org.openide.util.Exceptions;

    9. public class DBConect {

    10. Connection con = null;

    11. public DBConect() {
    12. Properties prop = System.getProperties();
    13. prop.put("derby.system.home",
      System.getProperty("user.home") + "/" + ".mesh");
    14. try {
    15. //start the database and get a connection
    16. con = DriverManager.
      getConnection("jdbc:derby:mesh_db", prop);
    17. } catch (SQLException e) {
    18. Exceptions.printStackTrace(e);
    19. }
    20. }

    21. public ResultSet executeQuery(String sql) throws SQLException {
    22. Statement statement = con.createStatement();
    23. return statement.executeQuery(sql);
    24. }

    25. public int executeUpdate(String sql) throws SQLException {
    26. Statement statement = con.createStatement();
    27. return statement.executeUpdate(sql);
    28. }
    29. }
  2. Now you can use this class to query the database or save data to the database using the two functions provided. This is a simple class. You can extend/modify it to do more complicated tasks.


No comments:

Post a Comment