import java.sql.*; import javax.sql.*; public class MyJDBCDriver implements Driver { public Connection connect(String url, Properties info) throws SQLException { } } import org.osgi.framework.*; public class MyActivator implements BundleActivator { public void start(BundleContext context) throws Exception { context.registerService(Driver.class.getName(), new MyJDBCDriver(), null); } public void stop(BundleContext context) throws Exception { } } import org.osgi.framework.*; import java.util.*; public class MyDatabaseService { private BundleContext context; public MyDatabaseService(BundleContext context) { this.context = context; } public Connection getConnection(String url, Properties info) throws SQLException { ServiceReference<Driver>[] driverRefs = context.getServiceReferences(Driver.class, null); for (ServiceReference<Driver> ref : driverRefs) { Driver driver = context.getService(ref); if (driver.acceptsURL(url)) { return driver.connect(url, info); } } throw new SQLException("No suitable JDBC driver found for URL: " + url); } } import java.sql.*; import java.util.*; public class MyDatabaseServiceClient { private MyDatabaseService databaseService; public MyDatabaseServiceClient(MyDatabaseService databaseService) { this.databaseService = databaseService; } public void executeQuery(String sql) throws SQLException { Properties info = new Properties(); info.put("user", "myuser"); info.put("password", "mypassword"); try (Connection connection = databaseService.getConnection("jdbc:mysql://localhost:3306/mydb", info); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { } } }


上一篇:
下一篇:
切换中文