Select data from MySQL database and put in R dataframe - sql

I can access a MySQL database and store output to an R dataframe using the following script where sam_pn = walker
con <- dbConnect(MySQL(),
user = user,
password = password,
host = host,
dbname = dbname)
df = dbGetQuery(con, "SELECT *
FROM sam AS s
JOIN che AS c ON c.che_label = s.sam_label1
WHERE sam_pn = 'walker'")
But what i would like to do is store 'walker' as an R value pn and then use pn value in the sql query like below so i can vary the pn value.... but it does not work. The syntax is not right. Note sam and che are tables in the database
pn = 'walker'
df = dbGetQuery(con, "SELECT *
FROM sam AS s
JOIN che AS c ON c.che_label = s.sam_label1
WHERE sam_pn = 'pn'")

pn = 'walker'
df = dbGetQuery(con, "SELECT *
FROM sam AS s
JOIN che AS c ON c.che_label = s.sam_label1
WHERE sam_pn = ?",
params = list(pn))

This is what worked in the end
pn = 'walker'
data = dbGetQuery(con, paste0("SELECT *
FROM sam AS s
JOIN che AS c ON c.che_label = s.sam_label1
WHERE sam_pn = '", pn ,"'"))

Related

SQL and r ”update fields”

SQL and r ”update fields”
Can anyone help Me.? i am trying to update fields in a row in a table on a sql server.
I have tried to send a vector with that contains the data I want to update(new_d), but I get an error every time I try to send the object with sql query. If I hardcode it, it works fine and the update goes through to the server.
what goes wrong when it does not want to send the object and what does it take to make it work? so it can save the update to the server
Hope anyone can show me what i do worng.
library(tidyverse)
library(readxl)
library(DT)
library(RODBC)
library(DBI)
library(odbc)
library(dbplyr)
# Connection is working ---------------------------------------------------
conn <- dbConnect(odbc(),
Driver = "ODBC Driver 13 for SQL Server",
Server = "IP, PORT",
Database = "DBNAME",
UID = "USERNAME",
PWD = "PASSWORD")
new_d <- c(name = 'Rap',
dateOfBirth = '1938-06-06',
city = 'Hollywood',
gender = 'Man',
time() = 8,
feeling = 'Happy')
# NOT WORKING -------------------------------------------------------------
update_statement1 <- build_sql("UPDATE ShinyTest
SET Name =?, City =?, Gender =?,
DateOfBirth =?, Time =?, Feeling =?
WHERE ShinyUserID = 4", new_d, con = conn)
update_statement1
# NOT WORKING -------------------------------------------------------------
update_statement2 <- build_sql("UPDATE ShinyTest
SET Name = name, City = city, Gender = gender,
DateOfBirth = dateOfBirth, Time = time, Feeling = feeling
WHERE ShinyUserID = 4", new_d, con = conn)
update_statement2
# NOT WORKING -------------------------------------------------------------
update_statement3 <- build_sql("UPDATE ShinyTest
SET Name = 'name', City = 'city', Gender = 'gender',
DateOfBirth = 'dateOfBirth', Time = 'time', Feeling = 'feeling'
WHERE ShinyUserID = 4", new_d, con = conn)
update_statement3
# NOT WORKING -------------------------------------------------------------
update_statement4 <- build_sql("UPDATE ShinyTest
SET Name = $name, City = $city, Gender = $gender,
DateOfBirth = $dateOfBirth, Time = $time, Feeling = $feeling
WHERE ShinyUserID = 4", new_d, con = conn)
update_statement4
# WORKING -------------------------------------------------------------
update_statement5 <- build_sql("UPDATE ShinyTest
SET Navn = 'Rap', City = 'Hollywood', Gender = 'Mand',
DateOfBirth = '1938-06-06', Tid = '8', Feeling = 'Glad'
WHERE ShinyUserID = 4", con = conn)
update_statement5
# NOT WORKING -------------------------------------------------------------
DBI::dbSendQuery(conn, update_statement1)
DBI::dbSendQuery(conn, update_statement2)
DBI::dbSendQuery(conn, update_statement3)
DBI::dbSendQuery(conn, update_statement4)
# WORKING -------------------------------------------------------------
DBI::dbSendQuery(conn, update_statement5)
DBI::dbDisconnect(conn)
# The Error i get ---------------------------------------------------------
#Error: nanodbc/nanodbc.cpp:1655: 42000: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Incorrect syntax near 'Rap'. [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Statement(s) could not be prepared.
#<SQL> 'UPDATE ShinyTest
# SET Navn = navn, City = city, Gender = gender,
# DateOfBirth = dateOfBirth, Tid = tid, Feeling = feeling
# WHERE ShinyUserID = 4('Rap', '1938-06-06', 'Hollywood', 'Mand', '8', 'Glad')'

How to use first query results in next query or first dataframe results use in next data frame

I am very new to spark and trying to get results from the first query and use that in the next query. But getting error
%pyspark
import sys
from pyspark.context import SparkContext
from pyspark.sql import SQLContext
from pyspark import *
sc = SparkContext.getOrCreate()
sqlContext = SQLContext(sc)
datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "adventure", table_name = "employee")
empDF = datasource0.toDF().where("age=40 and dept=10")
empDF.createOrReplaceTempView("empDF")
datasource1 = glueContext.create_dynamic_frame.from_catalog(database = "adventure", table_name = "dept")
deptDF = datasource1.toDF()
deptDF.createOrReplaceTempView("deptDF")
queryDF = sqlContext.sql("select * rom empDF e join deptDF d on e.id = d.id and d.manag=5")
datasource2 = glueContext.create_dynamic_frame.from_catalog(database = "adventure", table_name = "salary")
salDF = datasource2.toDF()
salDF.createOrReplaceTempView("salDF")
Now I want to join queryDF and salDF but it is giving me error saying query not found. how do i save the results of the first query to the table so I can use it in the second query?
finaDF = sqlContext.sql("select * rom queryDF e join salDF d on e.id = d.id").show()
You can do that directly in python using pyspark join
In your case that'd be:
finaDF = deptDF.join(salDF, "id")

Passing python list in hive query as parameters

from tkinter import *
import pyodbc
with pyodbc.connect("DSN=ffff", autocommit=True) as conn:
df2 = pd.read_sql("SELECT * FROM holdingsummarysaaas", conn)
list46 = []
for md in df2['clientcode']:
list46.append(md)
print(list46)
result = []
for i in list46:
if i not in result:
result.append(i)
print(result)
#list_no_nan = [x for x in result if pd.notnull(x)]
#print(list_no_nan)
#select name from studens where id in (%s)" % ",".join(map(str,mylist)
#def fun():
num1 = Entry(root)
blank = Entry(root)
Ans = (num1.get())
blank.insert(0, Ans)
if Ans in result:
df2 = pd.read_sql('SELECT * FROM holdingsummary where ' + ' or '.join(('clientcode = '
+ str(n) for n in result)),conn)
#df2 = pd.read_sql("SELECT * FROM holdingsummary where clientcode = '" + Ans + "'",
conn)
print(df2)
I am taking unique clientcodes from database and I want user input which is in fun
function should access the results list(unique clientcode )check each clientcode from list
and check whether entered clientcode if same in result list then open that clientcode.
for eg:
Ans=='100014'
#df2 = pd.read_sql("SELECT * FROM holdingsummarysaaas where clientcode = '100014', conn)

Why is this dropdown not populating?

I have three dropdowns; the second one (Members) populates based on what's in the first (Units), and the third one (Customers) SHOULD populate based on what's in the second; but it doesn't.
Here's the query that works in LINQPad (returns a list of Company names):
select distinct companyname from customers C left join members M on M.MemberNo = C.MemberNo where M.MemberNo = '052' order by companyname
...but does not work in the following code:
'Populate the Members dropdown
Dim selectedUnit As String = DropDownListUnits.Text
Dim membersDT As DataTable
sql = "select distinct shortname, M.memberno from members M left join memberunitproducts mup on M.MemberNo = mup.MemberNo where unit = '" + selectedUnit + "' order by shortname"
retDS = sqlDAL.runSQLDataSet(sql)
membersDT = retDS.Tables(0)
DropDownListMembers.DataSource = membersDT
DropDownListMembers.DataTextField = "shortname"
DropDownListMembers.DataValueField = "memberno"
DropDownListMembers.DataBind()
'Populate the Customers dropdown
Dim selectedMember As String = DropDownListMembers.DataValueField
Dim customersDT As DataTable
sql = "select distinct companyname from customers C left join members M on M.MemberNo = C.MemberNo where M.MemberNo = '" + selectedMember + "' order by companyname"
retDS = sqlDAL.runSQLDataSet(sql)
customersDT = retDS.Tables(0)
DropDownListCustomers.DataSource = customersDT
DropDownListCustomers.DataTextField = "companyname"
DropDownListCustomers.DataValueField = "companyname"
DropDownListCustomers.DataBind()
The third (Customers) dropdown remains unpopulated when this runs - why?
It's probably not needed, but here is the code for the first ("Units") dropdown:
'Populate the Units dropdown
Dim unitsDT As DataTable
sql = "Select distinct unit from masterunits where abs(active) = 1"
retDS = sqlDAL.runSQLDataSet(sql)
unitsDT = retDS.Tables(0)
DropDownListUnits.DataSource = unitsDT
DropDownListUnits.DataTextField = "unit"
DropDownListUnits.DataValueField = "unit"
DropDownListUnits.DataBind()
What am I missing or doing wrong?
I had to change this:
Dim selectedMember As String = DropDownListMembers.DataValueField
...to this:
Dim selectedMember As String = DropDownListMembers.SelectedItem.Value

linq to sql The Grid view

I make sales and procurement system and when I work a query, or search the invoice number, the results appear in palm leaves View, but appears only in a row while the bill by no more than one row
And this was used by code
i.m used vb.net and database sql and b yway linq to sql
Try
Dim data = (From d In DBVariable.Data.masterfatoras
From f In DBVariable.Data.fatoras
From na In DBVariable.Data.asnafs
From sup In DBVariable.Data.suppliers
Where d.ID = f.mid Where d.num.Contains(txt)
Select d, f, na, sup).FirstOrDefault
TextBoxX1.Text = data.d.num
nammord.Text = (From supp In DBVariable.Data.suppliers Where data.d.idmord = supp.ID Select supp.Name).Single()
txtmord.Text = (From supp In DBVariable.Data.suppliers Where data.d.idmord = supp.ID Select supp.Code).Single()
adrmord.Text = (From supp In DBVariable.Data.suppliers Where data.d.idmord = supp.ID Select supp.Address).Single()
nodaf.Text = data.d.nodfa
' ''نفاصيل الفاتورة
For p As Integer = 0 To gridshraa.Rows.Count - 1
gridshraa.Rows(p).Cells(2).Value = (From asna In DBVariable.Data.asnafs Where data.f.idname = asna.ID Select asna.Name).Single()
gridshraa.Rows(p).Cells(1).Value = (From asna In DBVariable.Data.asnafs Where data.f.idname = asna.ID Select asna.code).Single()
gridshraa.Rows(p).Cells(3).Value = (From asna In DBVariable.Data.asnafs Where data.f.idname = asna.ID Select asna.unit).Single()
gridshraa.Rows(p).Cells(4).Value = data.f.qty
gridshraa.Rows(p).Cells(5).Value = data.f.price
gridshraa.Rows(p).Cells(6).Value = data.f.totprice
Next
Catch
End Try