看完基于串口和Socket的bundle实现,本文中我们来看看bundle中如何实现数据库的访问。
先来看看DatabaseBundle.java(数据库使用的是MySQL,并且已经创建了一个名为demo_db的数据库和一个名为user_table的表用来保存用户名和密码)
- package demo.database.bundle;
- import java.sql.*;
- public class DatabaseBundle {
- protected static Connection con = null;
- static String driver = "com.mysql.jdbc.Driver";
- static String PGUrl = "jdbc:mysql://192.168.0.1/demo_db";
- static String PGUser = "demo";
- static String PGPasswd = "demo";
- public static Statement stmt = null;
- public static void openConnection() {
- try {
- Class.forName(driver);
- con = DriverManager.getConnection(PGUrl, PGUser, PGPasswd);
- } catch (Exception ex) {
- System.err.println("connection failed!");
- ex.printStackTrace();
- return;
- }
- }
- public static void closeConnection()
- {
- if(con != null) {
- try {
- con.close();
- } catch (Exception ex) {
- return;
- }
- }
- }
- public static void updateUserTable(String id, String pass, String fullname)
- {
- int idnumber = 1;
- try {
- String sql = "INSERT INTO user_table (id_number, id, pass, fullname) VALUES (" +
- idnumber + "," +
- id + "," +
- fullname + ")";
- //System.out.println(sql);
- Statement stmt = con.createStatement();
- stmt.executeUpdate(sql);
- } catch (Exception ex) {
- System.out.println("SQL Error!)");
- return;
- }
- }
- }
再来看看Activator.java
- package demo.database.bundle;
- import org.osgi.framework.BundleActivator;
- import org.osgi.framework.BundleContext;
- public class Activator implements BundleActivator {
- public void start(BundleContext context) throws Exception {
- System.out.println("Database Bundle started!");
- DatabaseBundle.openConnection();
- DatabaseBundle.updateUserTable("0", "123456", "test_name");
- }
- public void stop(BundleContext context) throws Exception {
- DatabaseBundle.closeConnection();
- System.out.println("Database Bundle stoped!");
- }
- }
运行该bundle, 即可发现user_table已经有记录被更新了,说明该bundle能访问数据库。
值得注意的一点是:只是把mysql-connector-java-5.1.22-bin.jar加进工程的lib之后编译和生成bundle没有问题,但启动bundle时会出错。必须在bundle.manifest文件中,把下面红色部分(com.mysql.jdbc)import进来才可以(如下所示)。而使用postgresql-jdbc-8.4.701.jar来访问基于PostgreSQL数据库时则无需Import此选项也没有问题。
Import-Package: org.osgi.framework,com.mysql.jdbc