Need to establish database connectivity in Drools - database

Need to establish database connectivity in drools to get some data as and when required while executing the rules. How do I go about that?

I have tried to establish Cassandra db connection from Drools file, It's working for me.
import com.datastax.driver.core.Cluster
import com.datastax.driver.core.Session
import com.datastax.driver.core.ResultSet;
function String ConnectDBase(String query) {
Session session;
Cluster cluster;
Cluster.Builder builder = Cluster.builder().
withoutJMXReporting().
addContactPoints("127.0.0.1");
cluster = builder.build();
session = cluster.connect("droolstest");
System.out.println("---------Execute Creation query-----------");
session.execute(query);
return "Table Created";
}
rule "DB Connectio
n rule"
when
//Write your code
then
String query = "CREATE TABLE emp(emp_id int PRIMARY KEY, "
+ "emp_name text, "
+ "emp_city text, "
+ "emp_sal varint, "
+ "emp_phone varint );";
System.out.println(ConnectDBase(query));
end

Drools function will look like as:
function String ConnectDB(String ConnectionClass,String url,String user, String password) {
Class.forName(ConnectionClass);
java.sql.Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from Employee where employee_id=199");
rs.first(); return rs.getString("employee_name");
}
Take a look at sample project https://github.com/abhijithumbe/jbpm6Examples/tree/master/Drools_DBConnection

Related

Change ResultSet to TYPE_SCROLL_INSENSITIVE in Scala

I'm using Scala to connect to a database. The connection is working and I can execute SQL with the output stored in a ResultSet. I now need to change the ResultSet to TYPE_SCROLL_INSENSITIVE so that I can point to specific rows in the ResultSet. This is a section of my code (connection details omitted for data privacy):
import java.sql.{Connection, ResultSet, SQLException, Statement}
object test extends App {
def connectURL (): java.sql. Connection = {
val url = "connection url"
val username = sys.env.get("USER").get
val password = sys.env.get("PASS").get
Class. forName ( "driver name" )
var connection = java.sql.DriverManager. getConnection ( url , username , password )
connection
}
val query = "SELECT * FROM TABLE1"
val con : java.sql. Connection = connectURL (); // creates the connection
val st = con . createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE); // creates connection statement
val rs = st.executeQuery(query); // executes the query and stores as ResultsSet
}
This gives the error: overloaded method value createStatement
The con variable is of type Connection, st is of type Statement and rs is of type ResultSet. I've tried changing val to the types above, and I get this error: value st is not a member of object java.sql.Statement
Any help would be much appreciated.
Please see javadocs https://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html
createStatement is defined with either 0,2, or 3 parameters

Java & SQL Server exception: The statement did not return a result set

I'm creating an insurance management system for my DBMS project in university, and I am having a problem with deleting a record from SQL Server. It throws an exception:
SqlException: com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
It also successfully deleted a record from my database. Could anyone please tell me how to remove this kind of exception?
String SQL="delete from INMS_3 where Agent_Id=? and First_Name=? and Last_Name=? and User_Name=? and Phone_no=?";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=INMS;user=TestingUser;password=1234;";
Connection con = DriverManager.getConnection(connectionUrl);
System.out.println("Connected to sql server");
String str=jTextField1.getText();
String str1=jTextField2.getText();
String str2=jTextField3.getText();
String str3=jTextField4.getText();
String str4=jTextField5.getText();
PreparedStatement st = con.prepareStatement(SQL);
st.setString(1, str);
st.setString(2,str1);
st.setString(3,str2);
st.setString(4,str3);
st.setString(5, str4);
ResultSet rs = st.executeQuery();
if(rs.next());
{
JOptionPane.showMessageDialog(null,"Deleted Succesfully");
}
if(!rs.next())
{
JOptionPane.showMessageDialog(null,"Unable to delete");
}
else
{
JOptionPane.showMessageDialog(null,"Unable to delete");
}
} catch (SQLException e) {
System.out.println("SQL Exception: "+ e.toString());
} catch (ClassNotFoundException cE) {
System.out.println("Class Not Found Exception: "+ cE.toString());
}
I think you are using the wrong thing to perform the delete operation.
Try using st.executeUpdate() instead of ResultSet rs = st.executeQuery() - you are executing a delete rather than something that would return a result set.
This is not a problem with SQL Server. The problem is with your code (what is that? C#? The object is set to expect a result set from the server, but the query is a DELETE statement, and those return no rows... ever.
State the programing language, and research for how to execute statement instead requesting result sets.
This line makes sense for a SELECT not for an UPDATE
ResultSet rs = st.executeQuery();
if you're executing a delete statement, why are you executing
ResultSet rs = st.executeQuery();
Here's a sample c# ado.net. concept it the same if you're using java.
using(var conn = new SqlConnection("my connection string"))
{
var deleteCmd = new SqlCommand();
deleteCmd.Connection = conn;
deleteCmd.CommandType = CommandType.Text;
deleteCmd.CommandText = #"
DELETE Accounts
WHERE account_id = #p_account_id
";
deleteCmd.Parameters.AddWithValue("p_account_id", 123);
conn.Open();
deleteCmd.ExecuteNonQuery();
}

Informix IfmxStatement.getSerial() to PostgreSQL substitute

Could you help me, because I have a problem? My task is to port a database from Informix to PostgreSQL, but someone use IfmxStatement method getSerial(), and I can't find any substitute for it in PostgreSQL.
Integer serial = new Integer(((IfmxStatement) stmt.getSerial());
You can use getGeneratedKeys() which is part of JDBC
stmt.executeUpdate("INSERT INTO ...", Statement.RETURN_GENERATED_KEYS);
// retrieve the auto generated key/keys
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next())
{
int serial = rs.getInt(1);
}
Thank you, this is my solution.
int serial=0;
ResultSet rs = null;
String query="SELECT nextval('id_seq');";
try
{
rs=stmt.executeQuery(query);
if (rs.next())
{
serial = rs.getInt(1);
}
setId(serial);

JDBC - prepareStatement - How should I use it?

I saw this example somewhere:
rs = connection.prepareStatement("select * from table").executeQuery();
Could I use this format, if I want to execute a query like this "Select * from table where column = "hello" "?
The way in which I usual I use prepareStatement object is something like this:
String sql = "select * from adresa where column = ?";
PreparedStatement pre = con.prepareStatement(sql);
pre.setString(1, i);
rs = pre.executeQuery();
Later Edit:
I don't understand. Pascal Thivent wrote that I can use the short version with In parameters, but Liu tells me this is not possible. :) Anw, using Pascal's version, i receive this error: void cannot be dereferenced
Here's a partial example how to use this interface:
static final String USER = "root";
static final String PASS = "newpass";
Connection conn = DriverManager.getConnection(myUrl, USER, PASS);
// create a sql date object so we can use it in our INSERT statement
Calendar calendar = Calendar.getInstance();
java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());
// the mysql insert statement
String query = " insert into students (ID, last_name, first_name, birthday, hometown)"
+ " values (?, ?, ?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, 808027);
preparedStmt.setString(2, "Davis");
preparedStmt.setString(3, "Felicita");
preparedStmt.setDate(4, startDate);
preparedStmt.setString(5, "Venice");
// execute the preparedstatement
preparedStmt.execute();
conn.close();
You can only use the first form if there are no bind variables (question marks) in the query. It's just a shortened version of what you posted.
Also, if you use the shortened form you won't have the opportunity to reuse the PreparedStatement object.
of course u can use a string variable for the query in which u put in ur dynamic data and run it.
rs = connection.prepareStatement(variable).executeQuery();
The long form is often, but prepared statements can be precompiled by the db, and if used properly will help prevent sql injection.
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
conn = getConn();
ps = conn.prepareStatement("select * from x where y = ? "); //note no sb.append()'s or +'s, to helps prevent sql injection
ps.setLong(1, 12l);
rs = ps.executeQuery();
while (rs.next()) {
... act ...
}
} catch ( Exception e) {
} finally {
if (rs != null) rs.close();
if (ps != null) ps.close();
if (conn != null) conn.close();
}
Who said java was verbose. :)

Exporting from SQLite to SQL Server

Is there a tool to migrate an SQLite database to SQL Server (both the structure and data)?
SQLite does have a .dump option to run at the command line. Though I prefer to use the SQLite Database Browser application for managing SQLite databases. You can export the structure and contents to a .sql file that can be read by just about anything. File > Export > Database to SQL file.
I know that this is old thread, but I think that this solution should be also here.
Install ODBC driver for SQLite
Run odbcad32 for x64 or C:\Windows\SysWOW64\odbcad32.exe for x86
Create SYSTEM DSN, where you select SQLite3 ODBC Driver
Then you fill up form where Database Name is filepath to sqlite database
Then in SQL Server run under sysadmin
USE [master]
GO
EXEC sp_addlinkedserver
#server = 'OldSQLite', -- connection name
#srvproduct = '', -- Can be blank but not NULL
#provider = 'MSDASQL',
#datasrc = 'SQLiteDNSName' -- name of the system DSN connection
GO
Then you can run your queries as normal user
e.g.
SELECT * INTO SQLServerDATA FROM openquery(SQLiteDNSName, 'select * from SQLiteData')
or you can use something like this for larger tables.
The SQLite .dump command will output the entire contents of the database as an ASCII text file. This file is in standard SQL format, so it can be imported into any SQL database.
More details on this page: sqlite3
sqlite-manager, firefox add-on: allows you to export an SQLite database in a SQL script.
Data Base>Export Database>Export to file
(Correction firefox 35 bugg obliged to correct the extension code as indicate to the following web page:
How to fix your optional sqlite manager module to work)
Command line :
sqlite3 DB_name .dump > DB_name.sql
exports the sqlite database in a SQL script.
From url : http://doc.ubuntu-fr.org/sqlite.
A idea is do some thing like this:
- View squema in sql lite and get the CREATE TABLE command.
- Execute, parsing sql, in SQL SERVER
- Travel data creating a INSERT statment for each row. (parsing sql too)
This code is beta, because no detect type data, and no use #parameter and command object, but run.
(You need insert reference and install System.Data.SQLite;)
c#:
Insert this code (or neccesari) in head cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Threading;
using System.Text.RegularExpressions;
using System.IO;
using log4net;
using System.Net;
public static Boolean SqLite2SqlServer(string sqlitePath, string connStringSqlServer)
{
String SqlInsert;
int i;
try
{
string sql = "select * from sqlite_master where type = 'table' and name like 'YouTable in SQL'";
string password = null;
string sql2run;
string tabla;
string sqliteConnString = CreateSQLiteConnectionString(sqlitePath, password);
//sqliteConnString = "data source=C:\\pro\\testconverter\\Origen\\FACTUNETWEB.DB;page size=4096;useutf16encoding=True";
using (SQLiteConnection sqconn = new SQLiteConnection(sqliteConnString))
{
sqconn.Open();
SQLiteCommand command = new SQLiteCommand(sql, sqconn);
SQLiteDataReader reader = command.ExecuteReader();
SqlConnection conn = new SqlConnection(connStringSqlServer);
conn.Open();
while (reader.Read())
{
//Console.WriteLine("Name: " + reader["name"] + "\tScore: " + reader["score"]);
sql2run = "" + reader["sql"];
tabla = "" + reader["name"];
/*
sql2run = "Drop table " + tabla;
SqlCommand cmd = new SqlCommand(sql2run, conn);
cmd.ExecuteNonQuery();
*/
sql2run = sql2run.Replace("COLLATE NOCASE", "");
sql2run = sql2run.Replace(" NUM", " TEXT");
SqlCommand cmd2 = new SqlCommand(sql2run, conn);
cmd2.ExecuteNonQuery();
// insertar los datos.
string sqlCmd = "Select * From " + tabla;
SQLiteCommand cmd = new SQLiteCommand(sqlCmd, sqconn);
SQLiteDataReader rs = cmd.ExecuteReader();
String valor = "";
String Valores = "";
String Campos = "";
String Campo = "";
while (rs.Read())
{
SqlInsert = "INSERT INTO " + tabla;
Campos = "";
Valores = "";
for ( i = 0; i < rs.FieldCount ; i++)
{
//valor = "" + rs.GetString(i);
//valor = "" + rs.GetName(i);
Campo = "" + rs.GetName(i);
valor = "" + rs.GetValue(i);
if (Valores != "")
{
Valores = Valores + ',';
Campos = Campos + ',';
}
Valores = Valores + "'" + valor + "'";
Campos = Campos + Campo;
}
SqlInsert = SqlInsert + "(" + Campos + ") Values (" + Valores + ")";
SqlCommand cmdInsert = new SqlCommand(SqlInsert, conn);
cmdInsert.ExecuteNonQuery();
}
}
}
return true;
} //END TRY
catch (Exception ex)
{
_log.Error("unexpected exception", ex);
throw;
} // catch
}
For Android.
adb root
adb shell
cd /data/com.xxx.package/databases/
sqlite3 db_name .dump >dump.sql

Resources