Using (Select * from a table ) to insert data into a table - python

I have bottom MySql query (sql1).
sq1 = 'select course_id, creator_id, max(course_num) + 1, recordid
' from Courses where recordid in' \
' (' + ','.join(map(str, RecordMatch1)) + ') group by recordid'
cursor.execute(sql1)
BTW, RecordMatch1 is an object that has matching data from other previous queries.
I am trying to see if this is possible; (select * from sql1) portion.
sql2 = ' insert into Courses (course_id, creator_id, course_num, record_id) '\
' Values ( select * from sql1)'
cursor.execute(sql2)
Or do I have to express everything rather than using (Select * )?
What is best practice?

You can do this, but you should specify columns in case of schema changes.

Just need to confirm you are trying to run a select query and insert its output to a insert query. If that is the case this appears to be good.

yes, you can but you should do something like
sql = "SELECT course_id, creator_id, course_num, record_id FROM Courses"
all = cursor.fetchall()
for i in range(len(all))
sql1 = "INSERT INTO Courses (course_id, creator_id, course_num, record_id) VALUES (%s, %s, %s, %s)"
cursor.execute(sql1, (all[i]['Key'], all[i]['Key2'], all[i]['Key3'], all[i]['Key3']))
you can change the select like you want, remember that return a dictionary so take care about the keys, add print(all) to see what happen with the select and see the keys of each column

Related

using sqlite3 and kivy

conn = sqlite3.connect('business_database.db')
c = conn.cursor()
c.execute("INSERT INTO business VALUES(self.nob_text_input.text, self.post_text_input.text, self.descrip_text_input.text )")
conn.commit()
conn.close()
I want to add records into my database using the TextInput in kivy hence the 'self.post_text_input.text' etc, but I get this error:
OperationalError: no such column: self.nob_text_input.text
I tried putting the columns next to table name in the query:
c.execute("INSERT INTO business(column1, column2,column3) VALUES(self.nob_text_input.text....)
But I still get the same error.
Turning my comment into a more detailed answer.
If you're trying to use the values of the variables (self.nob_text_input.text and friends) in the string, you need to embed those values in the string.
One way is to use a format string:
"INSERT INTO business VALUES(%s, %s, %s)" % (self.nob_text_input.text, self.post_text_input.text, self.descrip_text_input.text)
And another is to just concatenate the strings:
"INSERT INTO business VALUES(" + self.nob_text_input.text + ", " + self.post_text_input.text + ", " + self.descrip_text_input.text + ")"

Convert MySQL query to Python

I am trying to write a SELECT query with a WHERE condition and ORDER BY.
I have the query in MySQL and would like to convert it to Python.
This is my Mysql-Query:
SELECT StoreId
, ProductCode
, TotalQuantity
FROM storeinvoicedetails
WHERE StoreId=1
ORDER BY ProductCode
This is what I tried in Python:
sql = "SELECT StoreId,ProductCode,TotalQuantity FROM storeinvoicedetails \
WHERE StoreId = '%d'" % (1) \
"ORDER BY '%s' '%s'" % ('ProductCode','ASC')
query = """SELECT StoreId,ProductCode,TotalQuantity FROM storeinvoicedetails WHERE StoreId={0} ORDER BY ProductCode ASC""".format(store_id)
> sql = "SELECT StoreId,ProductCode,TotalQuantity FROM storeinvoicedetails \
WHERE StoreId = '%d' \
ORDER BY ProductCode ASC" % id
This should work.
STOREID = 1
# make sure you add the last space for every line, otherwise it will look like 'TotalQuantityFROM' causing an error
myQuery = "SELECT StoreId,ProductCode,TotalQuantity " +
"FROM storeinvoicedetails " +
"WHERE StoreId=" + str(STOREID) + " "
"ORDER BY ProductCode"

Select data from previous result of data

Sorry. I am new to expressing SQL statement in Python.
I am trying to do "Select x .. " from previous result of query.
For example, I have a first query (sql1):
sql1 = 'select course_id, record_id from Courses ' \
' where ( record_id not in ("TEST", "TEST123")) '
cursor.execute(sql1)
e = cursor.fetachall()
When I tried to do it without breaking down queries, I got an error due to different data type.
Now, how do I go about selecting from sql1 (this time I have to add one calculation of data) ?
sql2 = ' select course_id, max(record_id) + 1 from ... ? '
make sql1 a subquery of sql2. For example:
"""select course_id, max(record_id) + 1 from
(select course_id, record_id from Courses
where record_id not in ('TEST', 'TEST123'))"""
You could use a view to store the query.
CREATE OR REPLACE VIEW v AS
select course_id, record_id from Courses
where ( record_id not in ("TEST", "TEST123"));
select course_id, max(record_id) + 1 from v;
With this you will need only one query with Python.
sql1 = 'CREATE OR REPLACE VIEW v AS
select course_id, record_id from Courses
where ( record_id not in ("TEST", "TEST123"));
select course_id, max(record_id) + 1 from v;'
cursor.execute(sql1)
e = cursor.fetachall()
More information about view: https://dev.mysql.com/doc/refman/5.7/en/create-view.html

WHERE IN Clause in python list [duplicate]

This question already has answers here:
imploding a list for use in a python MySQLDB IN clause
(8 answers)
Closed 1 year ago.
I need to pass a batch of parameters to mysql in python. Here is my code:
sql = """ SELECT * from my_table WHERE name IN (%s) AND id=%(Id)s AND puid=%(Puid)s"""
params = {'Id':id,'Puid' : pid}
in_p=', '.join(list(map(lambda x: '%s', names)))
sql = sql %in_p
cursor.execute(sql, names) #todo: add params to sql clause
The problem is I want to pass the name list to sql IN clause, meanwhile I also want to pass the id and puid as parameters to the sql query clause. How do I implement these in python?
Think about the arguments to cursor.execute that you want. You want to ultimately execute
cursor.execute("SELECT * FROM my_table WHERE name IN (%s, %s, %s) AND id = %s AND puid = %s;", ["name1", "name2", "name3", id, pid])
How do you get there? The tricky part is getting the variable number of %ss right in the IN clause. The solution, as you probably saw from this answer is to dynamically build it and %-format it into the string.
in_p = ', '.join(list(map(lambda x: '%s', names)))
sql = "SELECT * FROM my_table WHERE name IN (%s) AND id = %s AND puid = %s;" % in_p
But this doesn't work. You get:
TypeError: not enough arguments for format string
It looks like Python is confused about the second two %ss, which you don't want to replace. The solution is to tell Python to treat those %ss differently by escaping the %:
sql = "SELECT * FROM my_table WHERE name IN (%s) AND id = %%s AND puid = %%s;" % in_p
Finally, to build the arguments and execute the query:
args = names + [id, pid]
cursor.execute(sql, args)
sql = """ SELECT * from my_table WHERE name IN (%s) AND id=%(Id)s AND puid=%(Puid)s""".replace("%s", "%(Clause)s")
print sql%{'Id':"x", 'Puid': "x", 'Clause': "x"}
This can help you.

Trouble with SQL in python

I have this Python code:
def get_employees(conditions, fields):
cursor.execute("SELECT employeeID FROM employees WHERE name=%s, budget=%s,
%year=%s,(some of conditions))
Is there any way to get employeeIDs if I set in conditions not all parameters, etc. only name and year?
If conditions were a dictionary, you could construct a query string:
def get_employees(conditions):
query = 'select employeeid from employees'
if conditions:
query += ' where ' + ' and '.join(key + ' = %s' for key in conditions.keys())
cursor.execute(query, conditions.values())
(I should note that here I am assuming that conditions does not have user-supplied keys. If there are user-supplied keys, this is definitely vulnerable to SQL injection.)
usually it is done via dynamic sql building, like this:
sql = "SELECT employeeID FROM employees WHERE 1=1";
if condition has name
sql += " and name='" .escape(name) . "'"
if condition has somefield
sql += " and somefield='" .escape(somefield) . "'"
etc
execute final sql

Categories