Cannot connect to DB2 Server From R Studio JDBC Driver - r

I have been trying to connect to my DB2 server for two days and have tried every post on here and have been unsuccessful to do so.
library(rJava)
library(RJDBC)
library(DBI)
#Enter the values for you database connection
dsn_driver = "com.ibm.db2.jcc.DB2Driver"
dsn_database = "D0042T04"
dsn_hostname = "DB2"
dsn_port = "50000"
dsn_protocol = "TCPIP"
dsn_uid = "db2User"
dsn_pwd = "secret!"
jcc = JDBC("com.ibm.db2.jcc.DB2Driver", "c:/development/R/db2jcc.jar");
path = "jdbc:db2://" + dsn_hostname + ":" + dsn_port + "/" + dsn_database + sep=""
jdbc_path = paste("jdbc:db2://", dsn_hostname, ":", dsn_port, "/", dsn_database, sep="");
conn = dbConnect(jcc, jdbc_path, user=dsn_uid, password=dsn_pwd)
query = "SELECT * FROM core.account FETCH FIRST 10 ROWS ONLY";
rs = dbSendQuery(conn, query);
df = fetch(rs, -1);
df
dbDisconnect(conn)
When I run the script I get the following
> query = "SELECT * FROM core.account FETCH FIRST 10 ROWS ONLY;";
> rs = dbSendQuery(conn, query);
Error in dbSendQuery(conn, query) : could not find function "dbSendQuery"

This seemed to work just fine.
https://www.r-bloggers.com/connecting-to-a-db2-database-from-r/

Related

Unable to reconnect to a socket

I am trying to connect to a socket using a client that is running Tkinter. The script runs a banking app allowing users to log in. The user data is stored in an SQLite database. When running the socket and client scripts the Tkinter window launches and the user is able to log in. However, when the user logs out and tries to log in as another user the program gets stuck.
LogInCommand() I think is getting stuck as it only fails when running again. I believe it has to do with how I am discounting from the socket. However, I need the socket to constantly run for the app to work.
Socket :
import socket
import sqlite3
Connection = sqlite3.connect('BankAccounts.sqlite')
st = socket.socket() #Creating a socket object. Second socket is the class.
print("socket ready")
st.bind(("Localhost",8080)) #Creating the socket using port 8080 (IP address + port number)
st.listen(100) #Only allowing a maximum of two connections at a time.
print("waiting for connections")
while True:
Client, address = st.accept() #Creating two variables and setting them equal to the accept object method.
# print("connected with", address)
print("Banking")
cdata = Client.recv(1024).decode()
print("in loop")
if not cdata:
break
if "*li#" in cdata:
print(cdata)
data = cdata.split("*li#")
cred = data[1].split("##")
sql = "SELECT * FROM bankusers"
curser = Connection.execute(sql)
username = cred[0]
password = cred[1]
for row in curser:
if row[0] == username and row[1] == password:
balance = str(row[2])
print(type(balance))
login = ("*Suc*"+balance)
print(login)
Client.send(bytes(f"{login}",'utf-8'))
Client.close()
Client :
from tkinter import *
from tkinter import *
from Bank import *
import socket
root = Tk()
Client = socket.socket()
Client.connect(("Localhost",8080))
import json
login = "Failed"
import sqlite3
Connection = sqlite3.connect('BankAccounts.sqlite')
def localuser(username,password,balance):
user1 = {
"username": username,
"password": password,
"balance" : balance
}
return user1
def sqlupdate():
with open("bankusers.json","r") as file:
reader = json.load(file)
balance2 = reader["balance"]
username2 = reader["username"]
print(balance2)
print(username2)
sql = f"UPDATE bankusers SET balance = {balance2} where username = '{username2}'"
Connection.execute(sql)
Connection.commit()
def updatenewuser(username, amount):
try:
sql1 = f"Select * from bankusers where username = '{username}' "
data = Connection.execute(sql1)
for row in data:
newbalance = int(row[2]) + int(amount)
sql2 = f"Update bankusers Set balance = {newbalance} where username = '{username}'"
Connection.execute(sql2)
except:
print("The user does not exist")
def logout():
canvas.delete("all")
label1 = Label(root,text = "Username")
label2 = Label(root,text = "Password")
global usernamebox
global passwordbox
usernamebox = Entry(root,width = 20)
passwordbox = Entry(root,width = 20)
buttonLogin = Button(root,text = "Login",width=10, command=LoginCommand)
canvas.create_window(230,100,window = label1)
canvas.create_window(230,150,window = label2)
canvas.create_window(400,100,window = usernamebox)
canvas.create_window(400,150,window = passwordbox)
canvas.create_window(400,200,window = buttonLogin)
canvas.pack()
def pay():
if name.get()==username1:
trylabel = Label(root,text= "You are unable to send money to yourself",)
canvas.create_window(400,250,window=trylabel)
else:
canvas.delete("all")
try:
sql2 = f"SELECT * FROM bankusers where username = '{username1}'"
curser = Connection.execute(sql2)
for row in curser:
if int(amountbox.get()) <= row[2]:
print("Sent")
newamount = row[2] - int(amountbox.get())
with open("bankusers.json", "w") as file:
user = localuser(username1,password1,newamount)
json.dump(user,file,indent=3)
sqlupdate()
updatenewuser(name.get(),int(amountbox.get()))
label1 = Label(root,text="Transaction Succsfull")
backbut = Button(root,text= "Done", command=mainscreen)
canvas.create_window(400,100,window=label1)
canvas.create_window(400,200,window=backbut)
else:
canvas.delete("all")
label1 = Label(root,text = "Transaction Failed. Please ensure you have suffcient funds for this transaction")
canvas.create_window(400,200,window=label1)
backbut = Button(root,text= "Done", command=mainscreen)
canvas.create_window(400,300,window=backbut)
except:
label1 = Label(root,text = "Transaction Failed. Please check recipient name and amount")
canvas.create_window(400,200,window=label1)
backbut = Button(root,text= "Done", command=mainscreen)
canvas.create_window(400,300,window=backbut)
def transact():
print("")
canvas.delete("all")
global name
label1 = Label(root,text = "Person Receiving:")
label2 = Label(root,text = "Amount:")
name = Entry(root,width = 20)
global amountbox
amountbox = Entry(root,width = 20)
paybutt = Button(root,text = "Pay", command = pay)
backbutton = Button(root,text = "Back",command = mainscreen)
canvas.create_window(350,300,window=backbutton)
canvas.create_window(450,100,window = name)
canvas.create_window(250,100,window=label1)
canvas.create_window(250,200,window=label2)
canvas.create_window(450,300,window=paybutt)
canvas.create_window(450,200,window=amountbox)
return
def LoginCommand():
count = 1
li = "*li#"
cred = li+usernamebox.get()+"##"+passwordbox.get()
Client.send((bytes(cred,"utf-8")))
message = Client.recv(1024).decode()
print(message)
if "*Suc*" in message:
count = 0
login = "Succsess"
global username1
global password1
global balance1
username1 = usernamebox.get()
password1 = passwordbox.get()
usernamebox.destroy()
passwordbox.destroy()
canvas.delete("all")
balance1 = message.split("*Suc*")
user = localuser(username1,password1,balance1[1])
with open("bankusers.json", "w") as file:
json.dump(user,file,indent=3)
mainscreen()
if count == 1:
global label2
label2 = Label(root,text = "Login Failed. Please Try Again")
canvas.create_window(400,250,window = label2)
def mainscreen():
with open("bankusers.json","r") as file:
reader = json.load(file)
balance2 = reader["balance"]
label2.destroy()
canvas.delete("all")
label1 = Label(root, text = f"Available Balance: R{balance2}")
buttonLogout = Button(root,text = "Log Out", command=logout)
buttonTrans = Button(root,text = "Transact", command=transact)
canvas.create_window(400,100,window = label1)
canvas.create_window(350,200,window=buttonLogout)
canvas.create_window(450,200,window = buttonTrans)
canvas.pack()
root.title("Raindrop Bank")
canvas = Canvas(root, width = 800, height = 400)
label1 = Label(root,text = "Username")
label2 = Label(root,text = "Password")
usernamebox = Entry(root,width = 20)
passwordbox = Entry(root,width = 20)
buttonLogin = Button(root,text = "Login",width=10, command=LoginCommand)
canvas.create_window(230,100,window = label1)
canvas.create_window(230,150,window = label2)
canvas.create_window(400,100,window = usernamebox)
canvas.create_window(400,150,window = passwordbox)
canvas.create_window(400,200,window = buttonLogin)
canvas.pack()
root.mainloop()

How to integrate database connection to R6 class in R

Hello I would like to assign a dbConnection to a R6 class but it fails.
LastProfilZdb <- R6Class(
classname = "LastProfilZdb",
public = list(
name = NULL,
zp = NULL,
data = NULL ,
zp_id = function() {
pool::poolWithTransaction(self$db_server, function(conn){
DBI::dbGetQuery(conn, paste0("SELECT ZP_ID FROM
ZP_ID WHERE LP_ZP = '", self$zaehlpunkt,
"' OR ZP_NAME_SAP = '", self$zaehlpunkt, "'"))
})
},
#....
#....
initialize = function(){
message("Init Data Base Connection")
#
self$db_server <- pool::dbPool(drv = odbc::odbc(),
dsn = "Oracle",
schema = "schema" )
},
finalize = function() {
message("Closing Data Base Connection")
pool::poolClose(self$db_server)
}
),
private = list(
# db Connection is stored in the calss so we don't need to care any more
# This way, input data can be collected in a neat way,
# and stored inside our object.
db_server = NULL
)
)
This fails with error:
Error in self$db_server <- pool::dbPool(drv = odbc::odbc(), dsn = "Oracle", :
cannot add bindings to a locked environment
What can I do?

How can I use last-of in a QUERY-PREPARE()?

I made a huge code and it was taking a very long time to process. Following suggestions here, I made it shorter and better and now it's running much faster. However, I noticed I should be getting a sum of the values whereas I'm just getting the values. I tried using ACCUMULATE TOTAL, but it didn't work because the LAST-OF can only be used with a BREAK BY and my break by is inside the QUERY-PREPARE().
How can I get the sum of the following values?
doc-fiscal.vl-cont-doc
doc-fiscal.vl-bicms
doc-fiscal.vl-icms
doc-fiscal.vl-icmsou
doc-fiscal.vl-ipiou
doc-fiscal.vl-ipi
Bellow is the code I'm using, which is working almost perfectly.
//Query
cQuery = "FOR EACH doc-fiscal WHERE doc-fiscal.dt-docto >= " + QUOTER(pd-data-1) + " AND doc-fiscal.dt-docto <= " + QUOTER(pd-data-2) + " AND (doc-fiscal.cod-observa <> 4 OR doc-fiscal.tipo-nat <> 3) AND doc-fiscal.cd-situacao <> 06 AND doc-fiscal.cd-situacao <> 22".
cQuery = cQuery + semCodEmitente + comCodEmitente + CheckBoxindSitDoc.
cQuery = cQuery + ", EACH natur-oper USE-INDEX natureza WHERE doc-fiscal.nat-operacao = natur-oper.nat-operacao" + modeloEletronico + tipoEntrada + natOper.
cQuery = cQuery + " BREAK BY doc-fiscal.dt-docto BY doc-fiscal.nr-doc-fis ".
QUERY qRelatorio:QUERY-PREPARE(cQuery).
QUERY qRelatorio:QUERY-OPEN().
GET FIRST qRelatorio.
DEF VAR soma-vl-cont-doc AS DECIMAL.
DO WHILE AVAILABLE doc-fiscal:
soma-vl-cont-doc = soma-vl-cont-doc + doc-fiscal.vl-cont-doc.
IF LAST-OF(doc-fiscal.nr-doc-fis) THEN DO:
CREATE tt-relatorio.
ASSIGN
tt-relatorio.nr-doc-fis = doc-fiscal.nr-doc-fis
tt-relatorio.serie = doc-fiscal.serie
tt-relatorio.char-2 = SUBSTRING(doc-fiscal.char-2,155,44, "CHAR")
tt-relatorio.cod-model-nf-eletro = natur-oper.cod-model-nf-eletro
tt-relatorio.tipo = natur-oper.tipo
tt-relatorio.cod-estabel = doc-fiscal.cod-estabel
tt-relatorio.cod-emitente = doc-fiscal.cod-emitente
tt-relatorio.nome-ab-emi = doc-fiscal.nome-ab-emi
tt-relatorio.cgc = doc-fiscal.cgc
tt-relatorio.dt-emis-doc = doc-fiscal.dt-emis-doc
tt-relatorio.dt-docto = doc-fiscal.dt-docto
tt-relatorio.ind-sit-doc = doc-fiscal.ind-sit-doc
tt-relatorio.vl-cont-doc = doc-fiscal.vl-cont-doc
tt-relatorio.vl-bicms = doc-fiscal.vl-bicms
tt-relatorio.vl-icms = doc-fiscal.vl-icms
tt-relatorio.vl-icmsou = doc-fiscal.vl-icmsou
tt-relatorio.vl-ipiou = doc-fiscal.vl-ipiou
tt-relatorio.vl-ipi = doc-fiscal.vl-ipi
tt-relatorio.imp-nota = natur-oper.imp-nota.
GET NEXT qRelatorio.
END.
END.
QUERY qRelatorio:QUERY-CLOSE().
Thanks for the help and sorry for being such a newbie. I hope my question can help other people.
I managed to do it.
I used LAST-OF() METHOD. My code became the following.
DEF VAR soma-vl-cont-doc AS DECIMAL. //INICIO DAS SOMAS
DEF VAR soma-vl-bicms AS DECIMAL.
DEF VAR soma-vl-icms AS DECIMAL.
DEF VAR soma-vl-icmsou AS DECIMAL.
DEF VAR soma-vl-ipiou AS DECIMAL.
DEF VAR soma-vl-ipi AS DECIMAL.
DO WHILE AVAILABLE doc-fiscal:
soma-vl-cont-doc = soma-vl-cont-doc + doc-fiscal.vl-cont-doc.
soma-vl-bicms = soma-vl-bicms + doc-fiscal.vl-bicms.
soma-vl-icms = soma-vl-icms + doc-fiscal.vl-icms.
soma-vl-icmsou = soma-vl-icmsou + doc-fiscal.vl-icmsou.
soma-vl-ipiou = soma-vl-ipiou + doc-fiscal.vl-ipiou.
soma-vl-ipi = soma-vl-ipi + doc-fiscal.vl-ipi.
IF QUERY qRelatorio:LAST-OF(2) THEN DO:
CREATE tt-relatorio.
ASSIGN
tt-relatorio.nr-doc-fis = doc-fiscal.nr-doc-fis
tt-relatorio.serie = doc-fiscal.serie
tt-relatorio.char-2 = SUBSTRING(doc-fiscal.char-2,155,44, "CHAR")
tt-relatorio.cod-model-nf-eletro = natur-oper.cod-model-nf-eletro
tt-relatorio.tipo = natur-oper.tipo
tt-relatorio.cod-estabel = doc-fiscal.cod-estabel
tt-relatorio.cod-emitente = doc-fiscal.cod-emitente
tt-relatorio.nome-ab-emi = doc-fiscal.nome-ab-emi
tt-relatorio.cgc = doc-fiscal.cgc
tt-relatorio.dt-emis-doc = doc-fiscal.dt-emis-doc
tt-relatorio.dt-docto = doc-fiscal.dt-docto
tt-relatorio.ind-sit-doc = doc-fiscal.ind-sit-doc
tt-relatorio.vl-cont-doc = soma-vl-cont-doc
tt-relatorio.vl-bicms = soma-vl-bicms
tt-relatorio.vl-icms = soma-vl-icms
tt-relatorio.vl-icmsou = soma-vl-icmsou
tt-relatorio.vl-ipiou = soma-vl-ipiou
tt-relatorio.vl-ipi = soma-vl-ipi
//tt-relatorio.idi-sit-nf-eletro = nota-fiscal.idi-sit-nf-eletro
tt-relatorio.imp-nota = natur-oper.imp-nota.
soma-vl-cont-doc = 0.
soma-vl-bicms = 0.
soma-vl-icms = 0.
soma-vl-icmsou = 0.
soma-vl-ipiou = 0.
soma-vl-ipi = 0.
END.
GET NEXT qRelatorio.
END.
With this, I managed to get the answers I wanted andthe query is quite fast. If there's any suggestions as to how make it faster, I'm open for them. Thanks.

Automatically Interaction between MVC and R projects in visual studio 2017

I have mvc project and R project under same solution, I want to run mvc first display it on browser then send some arguments to script.R in R project then run R project and refreshing mvc based on results of R project
Currently I can execute Script.r and the results saved as html then I run mvc and html results from R are displayed on the browser.
I need to make it automatically.
My code is like this code https://1drv.ms/u/s!Ar6hTIP_Ln58h6JtpQQ3yt3JjIsIFg
Controller code
using WebApplication1.Infrastructure;
public ActionResult Index()
{
RScript.Run("HeatMap", 1997);
RScript.Run("HeatMap", 1998);
return View();
}
Rscript class code
public static class RScript
{
public static bool Run(string filename, int year = 0)
{
var rCodeFilePath = $"C:\\Users\\COMNET\\source\\repos\\Test\\RProject1\\RProject1\\{filename}.R";
if (year != 0)
rCodeFilePath = $"{rCodeFilePath} {year}";
var rScriptExecutablePath = #"C:\Program Files\R\R-3.4.3\bin\x64\Rscript.exe";
var result = string.Empty;
try
{
var info = new ProcessStartInfo
{
FileName = rScriptExecutablePath,
WorkingDirectory =
Path.GetDirectoryName(rScriptExecutablePath),
Arguments = rCodeFilePath,
RedirectStandardInput = false,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (var proc = new Process())
{
proc.StartInfo = info;
proc.Start();
proc.Close();
}
return true;
}
catch (Exception ex)
{
//return false;
throw new Exception("R Script failed: " + result, ex);
}
}
}
R script code
library(RODBC)
library(ggplot2)
args <- commandArgs(TRUE)
cn <- odbcConnect('', uid = '', pwd = '')
view <- ifelse(args[1] == 1998, 'vwR1TranValuebyCountryCategoty98', 'vwR1TranValuebyCountryCategoty97')
qtyNatCat <- sqlFetch(cn, view)
odbcClose(cn)
q <- ggplot(qtyNatCat, aes(x = Category, y = Country, fill = TransValue))
q <- q + geomtile()
q <- q + geomraster()
q <- q + scalefillgradient(low = "#c00000", high = "#00c000", na.value = "white")
q <- q + xlab('') + ylab('')
q <- q + theme(axis.text.x = elementtext(angle = 10, hjust = 1, vjust = 1))
q <- q + labs(fill = "Qty\nper\nTran")
wd <- getwd()
imagedir <- paste("C:\\Users\\COMNET\\Downloads\\net to the power of r\\NorthwindDashboard\\NorthwindDashboard\\Content\\html\\", sep = "")
setwd(imagedir)
filename <- ifelse(args[1] == 1998, 'heatmap98.png', 'heatmap97.png')
if (file.exists(filename))
file.remove(filename)
ggsave(q, file = filename, width = 9, height = 4)
setwd(wd)

How to send nicely formatted mails in R

I use below mentioned code to send mails, can I change the format of table which will pasted on mail body, I want to send nicely formatted/compacted table in mail body.
first6 is my data.frame
Date=sys.Date()-1
date2 <- paste("My subject of mail", Date, sep = " - ")
setwd("/xyz")
newdir <- paste("output", Sys.time(), sep = "_")
dir.create(newdir)#, showWarnings = FALSE)
setwd(newdir)
######
mydoc = bsdoc( title = 'my document')
options( "ReporteRs-fontsize" = 8 )
mydoc = addParagraph(mydoc, value = "Hi All, \n\nPlease check attached summary.")
mydoc = addParagraph(mydoc, value = "Summary:")
MyFTable = FlexTable( data = first6, add.rownames = FALSE, header.cell.props = cellProperties( background.color = "#FAEBD7" )
, header.par.props = parProperties(text.align = "center" ))
MyFTable = setColumnsColors( MyFTable, j=1, colors = '#F0F8FF' )
MyFTable[ , ] = parProperties( text.align = 'center')
MyFTable = setColumnsColors( MyFTable, j=ncol(first6), colors = '#F0F8FF' )
mydoc = addFlexTable( mydoc, MyFTable )
writeDoc( mydoc, file = "op2.html" )
send.mail(from = "abc#xyz.com",
to = c("abc#xyz.com"),
subject = date2,
body = "op2.html",
html = TRUE,
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "abc#xyz.com", passwd = "xyz#123", ssl = TRUE),
authenticate = TRUE,
send = TRUE)
Sorry if this doesn't answer your question, but I think you need to use the right tool for the right job.
In column A : Names of the people
In column B : E-mail addresses
In column C:Z : Filenames like this C:\Data\Book2.xls (don't have to be Excel files)
The Macro will loop through each row in "Sheet1" and if there is a E-mail address in column B
and file name(s) in column C:Z it will create a mail with this information and send it.
Sub Send_Files()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sh = Sheets("Sheet1")
Set OutApp = CreateObject("Outlook.Application")
For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants)
'Enter the path/file names in the C:Z column in each row
Set rng = sh.Cells(cell.Row, 1).Range("C1:Z1")
If cell.Value Like "?*#?*.?*" And _
Application.WorksheetFunction.CountA(rng) > 0 Then
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = cell.Value
.Subject = "Testfile"
.Body = "Hi " & cell.Offset(0, -1).Value
For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
If Trim(FileCell) <> "" Then
If Dir(FileCell.Value) <> "" Then
.Attachments.Add FileCell.Value
End If
End If
Next FileCell
.Send 'Or use .Display
End With
Set OutMail = Nothing
End If
Next cell
Set OutApp = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
You can find other options at the link below.
https://www.rondebruin.nl/win/s1/outlook/mail.htm

Resources