Search code examples
sqlapache-camelapache-servicemix

Sql Connection in Spring Servicemix camel


Sql Connection in Spring Servicemix camel

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
    <property name="url" value="jdbc:sqlserver://localhost:1433/orderdb"/>
    <property name="username" value="abc"/>
    <property name="password" value="pqr"/>
</bean>

When I try to make connection using dataSource.getConnection()

Not allowing please help

*****Connection Code **********

public class DatabaseBeanH2 {

    private DataSource dataSource;
    private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseBeanH2.class);

    public DatabaseBeanH2(){}

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void create() throws SQLException{
        Statement sta = dataSource.getConnection().createStatement();
        try {
            sta.executeUpdate("CREATE TABLE orders ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, item VARCHAR(50), amount INT, description VARCHAR(300), processed BOOLEAN, consumed BOOLEAN);");
        } catch (SQLException e) {
            LOGGER.info("Table orders already exists");
        }
    }

    public void destroy() throws SQLException {
        dataSource.getConnection().close();
    }
}

Solution

  • You have to setting up your database using following code

    <!-- this is the JDBC data source which uses an in-memory only Apache Derby database -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver"/>
    <property name="url" value="jdbc:derby:memory:orders;create=true"/>
    <property name="username" value=""/>
    <property name="password" value=""/>
    </bean>
    
    <!-- bean which creates/destroys the database table for this example -->
    <bean id="initDatabase" class="org.apache.camel.example.sql.DatabaseBean"
      init-method="create" destroy-method="destroy">
    <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- configure the Camel SQL component to use the JDBC data source -->
    <bean id="sql" class="org.apache.camel.component.sql.SqlComponent">
    <property name="dataSource" ref="dataSource"/>
    </bean>
    

    Please check this link http://camel.apache.org/sql-example.html