Вопрос:

How to connect a Database(MySql) with drools project?

java mysql drools mysqlconnection

585 просмотра

1 ответ

11 Репутация автора

I have created three classes and and tried to set them values through main class by connecting it into database. Then i am trying to fire the rules, but i am not getting the output. I have to fetch the values from database and set them to the variables of the three classes.

static int pid;
static int mrp;
static int cid;
static float tax;
static String pname;
static String cname;
public static void main(String[] args)
{

    try
    {
    Class.forName("com.mysql.jdbc.Driver");
    Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/abhi","root","abhinav");
    Statement ps=cn.createStatement()   ;
    ResultSet rs=ps.executeQuery("select * from product ");
    while(rs.next())
    {
     pid=rs.getInt(1);
     pname=rs.getString(2);
    mrp=rs.getInt(3);
    }
    Statement ps1=cn.createStatement();
    ResultSet rs1=ps1.executeQuery("select * from city");


    while(rs1.next())
    {
        cid=rs1.getInt(1);
        cname=rs1.getString(2);
    }
    Statement ps2=cn.createStatement();
    ResultSet rs2=ps2.executeQuery("select * from tax");
    while(rs2.next())
    {
        cid=rs2.getInt(1);
        pid=rs2.getInt(2);
        tax=rs2.getFloat(3);
    }


    KnowledgeBase kbase = readKnowledgeBase();
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    Product p=new Product();
    p.setPid(pid);
    p.setPname(pname);
    p.setMrp(mrp);
    ksession.insert(p);
    City c=new City();
    c.setCid(cid);
    c.setCname(cname);
    ksession.insert(c);
    Tax t=new Tax();
    t.setCid(cid);
    t.setPid(pid);
    t.setTax(tax);
    ksession.insert(t);
    ksession.fireAllRules();
    }
    catch(Throwable t)
    {
        t.printStackTrace();
    }
Автор: Abhinav Bhushan Jha Источник Размещён: 17.04.2017 05:18

Ответы (1)


0 плюса

28740 Репутация автора

You'll have to insert one object as a fact for each result of a query, e.g.

ResultSet rs=ps.executeQuery("select * from product ");
while(rs.next()){
  int pid = rs.getInt(1);
  String pname = rs.getString(2);
  int mrp = rs.getInt(3);
  Product p = new Product();
  p.setPid(pid);
  p.setPname(pname);
  p.setMrp(mrp);
  ksession.insert(p);
}

// same for City and Tax ...

ksession.fireAllRules();

Declare variables where they are used. (Using a global cid for city and tax could easily lead to an error.)

Автор: laune Размещён: 17.04.2017 05:44
Вопросы из категории :
32x32