I have the following sql query:
SELECT
pc.patente,
cs.cpc_group_codigo_cpc_group
FROM
patente_pc pc
,
patente_cpc cpc,
cpc_subgroup cs,
cpc_group cg
WHERE
pc.codigo_patente_pc = cpc.patente_pc_codigo_patente_pc AND
cpc.cpc = cs.codigo_cpc_subgroup AND
cs.cpc_group_codigo_cpc_group = cg.codigo_cpc_group
GROUP BY
pc.patente, cs.cpc_group_codigo_cpc_group
I add this query to python, separating line by line the string in a tuple to not have a problem with the syntax..
and it executes correctly
but when I need to retrieve the data, I use
lista_cpcs = []
lista_patentes = []
for (pc.patente, cs.cpc_group_codigo_cpc_group) in cursor:
lista_cpcs.append(cs.cpc_group_codigo_cpc_group)
lista_patentes.append(pc.patente)
return [lista_cpcs, lista_patentes]
and I get the error Global name 'pc' is not defined
I get whats happening, it's interpreting pc and cs as python modules, but they are from the sql..
how to work in this?
Ps: I search for python mysql connector and didn't found anything with this.
The variables in your for loop: (pc.patente, cs.cpc_group_codigo_cpc_group) are user defined; the names used do not have anything to do with the names from the query. Thus, you can call them whatever you want. You may consider using (pc__patente, cs__cpc_group_codigo_cpc_group) or something.
The problem is that the dot notation in python != the dot notation from your SQL.
Got it, sorry for the post..
Searching in https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-description.html
I learned a few attributes of the cursor, and using the Eclipse debugger I saw that it comes just the name, not the table connection..so I use
for (patente, cpc_group_codigo_cpc_group) in cursor:
lista_cpcs.append(cpc_group_codigo_cpc_group)
lista_patentes.append(patente)
and it's working now, and thanks for the help #Scott
Related
I got around 500 lines of sqlite code and i am trying to reduce that number. So i tried making a function with variables.
I tried using this code:
x = "c.execute("
o = "'"
y = "'INSERT INTO "
unio = x+y
tabl = ["d","d_2","n_d","n_d_2"]
val = "VALUES ("
w = ") "
k = "?,?"
mark = 369
ek = 963
def db_up(table,):
aa = y+table+"("+tabl[0] + ", " + tabl[1]+w+val+k+")"+"',"+"(mark,ek,)"
bb = unio+table+"("+tabl[1]+ ", " + tabl[1]+w+val+k+")"+"',"+"(mark,ek,))"
print(aa) # 'INSERT INTO avg_dt(d, d_2) VALUES (?,?)',(mark,ek,)
print(bb) # c.execute('INSERT INTO avg_dt(d_2, d_2) VALUES (?,?)',(mark,ek,))
c.execute(str(aa)) # no succes
c.execute(aa) # no success
bb # no success
When i run the "c.execute(aa)" line. it throws me this error:
sqlite3.OperationalError: near "'INSERT INTO avg_dt(d, d_2) VALUES (?,?)'": syntax error
So...how can i make a sqlite3 code using variables a functions?
Thanks for taking the time ;)
I can't post a comment with my current rep, so let me try to provide a full answer.
Your approach seems to be that you have too much SQL code, which you consider a problem, so you're trying to "compress" the code by reducing common statements into shorter variable names. There are a number of reasons you should avoid doing this, and a number of better ways to achieve a similar result.
First, let's talk about why this is a bad idea:
Your code doesn't become more maintainable. Interspersing cryptic variable names like x, o, y, or unio doesn't make the code any easier to read, even for the author, assuming a few days have passed since you wrote it.
Using this kind of method doesn't make your code any more performant, and most likely makes it less performant: your program now has to worry about allocating and reallocating memory when doing string interpolation or concatenation, which takes cycles.
Doing string interpolation or concatenation in SQL should be done with extreme caution: this is essentially a homebrew version of prepared statements, which are usually authored by people with loads of experience doing SQL programming. Making this on your own risks your program being targetted by SQL injection (or at least column/value type mismatches).
Now, let's talk about mitigating this issue for you:
Lots of SQL code need not be unmanageable: typically, if you must maintain large amounts of raw SQL in your project, you dump that into a separate SQL file which you can then either execute directly from the database CLI or run from your program via a database driver.
ORMs are (usually) your friend: with the exception of exotic or outstandingly performance-sensitive SQL queries, modern ORMs can get rid of most raw SQL code in your program. The more naturally programmatic structure of ORM code also means you can break it up into different delegate functions to avoid code reuse, to an extent.
Please feel free to add details to your question; as it stands, it's not totally clear whether your concerns can be addressed with this answer.
I have inherited a set of Python code, and I think I know the answer to this, but wish to be sure.
It looks like both #s and --s are used interchangeably throughout the code to signify comments but any searches I am doing do not yield information about using the --.
I used to do the --s within Teradata a long time ago. Am I missing something?
Adding in some additional information too: I am running the code within Spyder (Python3.6). Perhaps that will shed more light on what is going on.
Below is an example of the -- seeming to work:
qry = """
select s2019.sk2019,
s2018.sk2018
from (select distinct h1.key sk2019,
e.Territory Territory2019 from cdw.fact_header
left join cdw.dim_event e on h1.event = e.event
where e.sy in (2019)
and e.program_name = 'xyz'
and a.Country = 'USA'
-- and h1.code = 'DC'
and h1.key > 0
One line comments are done using the # while multiline comments are done using the triple-quote
""" Text here
and here"""
the -- comment is used in sqlite with python. Do you have that comment inside a query that is also written inside a string/triple-quote comment? Like:
""" SELECT * FROM TABLE
--WHERE N = X"""
UPDATE 1:
Here you can see and example of comment inside the query done in a python code
query = """ SELECT * FROM TABLE
--WHERE N = X"""
By putting -- inside the query, before WHERE I've made everything that follows ignored. So when the query is executed I will only execute the first line of the query.
I'm writing code that takes a user-inputted string and binds it to a SQLite command through a parameter.
I've gotten this functionality to work when the string is already embedded in the query (see first example under "these lines do work"), and this binding method works with integers just fine (see second example).
testname = "\"EJtheDJ\"" #this would be user-inputted, but I get the same issue when I initialize it this way
#this line doesn't work
c.execute("select lastfm from usernames where discordname=?", (testname,))
#these lines do work
#c.execute("select lastfm from usernames where discordname=\"EJtheDJ\"")
#c.execute("select integer1 from test where integer2=?", (num,)) #num=3
print(c.fetchone()) #prints out "None"
My syntax seems 100% correct according to all the tutorials and forum threads I've looked at. I don't normally make posts here (in fact this is my first time), but I'm completely stumped on this and felt it was my only option. Any help would be massively appreciated. I'm running this on a CentOS server with Python 3.6, if that helps.
Edit: Turns out I just needed to do away with the escaped quotes. testname = EJtheDJ works perfectly.
I am looking to implement full text search in my python application using pymongo. I have been looking at this question but for some reason I am unable to implement this in my project as I am getting an error no such cmd: text. Can anyone direct me on what I am doing wrong?
Here is my code:
db = client.test
collection = db.videos
def search_for_videos(self, search_text)
self.db.command("text", "videos",
search=search_text,
limit=10)
The collection I am trying to search is called videos however I am not sure if I am putting this in the correct parameter, and I also am not sure if I need the line project={"name": 1, "_id": 0}.
The documentation here I believe is using the mongo shell to execute commands, however I wish to perform this action in my code.
I have looked at using the db.videos.find() function, but cannot seem to implement it correctly either.
How to I use PyMongo Full Text Search from my Python Code?
First be sure that you have a text index created on the field as mentioned here or you can just do it with pymongo too :
collection.create_index([('your field', 'text')])
Using pymongo you can do this to search:
collection.find({"$text": {"$search": your search}})
your function should look like this:
def search_for_videos(search_text):
collection.find({"$text": {"$search": search_text}}).limit(10)
I hope this helps you.
First create a text index based on the field you want to do the search on.
from pymongo import TEXT
db = MongoClient('localhost',port = 27017).DBNAME
db.collection.create_index([('FIELD_NAME',TEXT)],default_language ="english")
once you create the text index use the following query to search text. Depending on the size of your database, it might take long to create the text index.
db.collection.find({"$text": {"$search": your search}})
>>> e=searchengine.searcher('searchindex.db')
>>> e.getmatchrows('functional programming') select w0.urlid,w0.location,w1.location from wordlocation w0,wordlocation w1 where w0.urlid=w1.urlid and w0.wordid=10 and w1.wordid=17
SyntaxError: invalid syntax
# it highlights the word select in the program
How do I correct this syntax error of the select statement? I am using Python with sqlite3.
You can't just plonk SQL into a python file. This error message is python telling you "I have no idea what select is".
To be more helpful, you'd need to share what library you got "searchengine" from, but no matter what that is, your code is not valid python, so there's no way it's going to work.