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

时间:2017-04-17 05:18:25

标签: java mysql drools mysqlconnection

我创建了三个类,并尝试通过将它们连接到数据库来通过主类设置它们。然后我试图解雇规则,但我没有得到输出。我必须从数据库中获取值并将它们设置为三个类的变量。

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

1 个答案:

答案 0 :(得分:0)

您必须为查询的每个结果插入一个对象,例如

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

声明使用它们的变量。 (对城市和税收使用全球cid很容易导致错误。)