简体   繁体   English

如何将数据库(MySql)与drools项目连接?

[英]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.) (对城市和税收使用全球cid很容易导致错误。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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