简体   繁体   中英

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

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();
    }

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

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM