I have a database with some records that have a date field of "05221999". I am trying to do a SQL query from the input of the user based on just the month and year. In this case I am interested in all the records with the month of 05 and the year of 1999.
Unfortunately, I can't get the Python/SQL syntax correct. Here is my code so far:
def submitact(self):
date = self.md.get()
month = date[0:2]
year = date[2:7]
db = pymysql.connect("localhost", "username", "password", "database")
cursor = db.cursor()
cursor.execute("SELECT * FROM `table` WHERE `Code` = 'RM' AND `Date` LIKE %s'_'%s", (month, year))
results = cursor.fetchall()
print(results)
cursor.close()
db.close()
I've done several variations on the SELECT statement and they either return errors or nothing.
Thanks!
In the code snippet below, I used f-string style to format the query string
[...]
query = f"SELECT * FROM `table` WHERE `Code` = 'RM' AND LEFT(`Date`, 2) = '{month}' AND RIGHT(`Date`, 4) = '{year}'"
cursor.execute(query)
[...]
try with this:
query = "SELECT * 'table' WHERE 'Code' = 'RM' AND 'Date' LIKE '%{0}_{1}'".format(month, year)
cursor.execute(query)
In this way, 'query' variable value will be:
"SELECT * FROM 'table' WHERE 'Code' = 'RM' AND 'Date' LIKE '%05_1999'"
For more information about string formatting, let's have a look to Python String Formatting Best Practices - Real Python
Related
I saved my data in databse where I created two columns with master_user and master_password.I inserted a value in my database. But somehow I am unable to find that master_user with my current code. error- sqlite3.OperationalError: no such column: animesh7370
def login(self):
conn = sqlite3.connect("master.db")
cur = conn.cursor()
#conn.execute("CREATE TABLE master_database (master_users TEXT NOT #NULL,master_password
#TEXT NOT NULL)")
#cur.execute("INSERT INTO master_database (master_users,master_password)
#VALUES('animesh7370','A#singh7')")
user = self.root.ids.user.text
password = self.root.ids.password.text
print(type(password))
cur.execute(f"SELECT * FROM master_database WHERE master_user = {user}")
#cur.execute("SELECT * FROM master_database ")
c=cur.fetchone()
for items in c:
print(items)
conn.commit()
conn.close()
Naming problem. You forgot the 's' to master_user.
cur.execute(f"SELECT * FROM master_database WHERE master_users = {user}")
HERE --^
cur.execute("SELECT * FROM master_database WHERE master_users =?" ,(user,))
This is because your resulting SQL looks like this (assuming that user is 'animesh7370'):
SELECT * FROM master_database WHERE master_user = animesh7370
Better use command parameters
select_stmt = "SELECT * FROM master_database WHERE master_users = %s"
cur.execute(select_stmt, (user,))
Note that command parameters are not simply inserted as a string concatenation but are passed to the query with the appropriate data type.
See: Passing parameters to SQL queries
You declared the column as master_users but referred to it as master_user in the select statement. It is usual to use column names in singular.
I am trying to clean raw json data by parsing and inserting it into a table of an sqlite db.
I have 22 columns in my table and want to find a way of looping through them so I don't need to write 22 loops which insert the data or a single column.
I have simplified the approach I am trying with the following:
import sqlite3
conn = sqlite3.connect('cdata.sqlite')
cur = conn.cursor()
column = 'name'
value = 'test'
cur.execute('''INSERT INTO COMPANY (?)
VALUES (?)''',(column,),(value,))
conn.commit()
conn.close()
This doesn't work at the moment and return the error TypeError: function takes at most 2 arguments (3 given).
Does anyone know if it is possible to write an SQLite insert statement using 2 parameters like this or another way I might be able to iterate through the columns?
Sample as below:
import sqlite3
conn = sqlite3.connect("cdata.sqlite")
cur = conn.cursor()
column = ("name", "age")
table = f"CREATE TABLE IF NOT EXISTS COMPANY ({column[0]} text, {column[1]} text);"
cur.execute(table)
name = "hello"
age = "1"
sql_stmt = f"INSERT INTO COMPANY({column[0]},{column[1]}) VALUES ('{name}', '{age}')"
cur.execute(sql_stmt)
with conn:
cur.execute("SELECT * FROM COMPANY")
print(cur.fetchall())
conn.commit()
conn.close()
I have tried doing some sql connectivity and faced a problem recently, i could'nt take isert dates into a table. I have given the code below. what should i add in this?
import mysql.connector as con
db = con.connect(host = "localhost", user = "root", password = "root", database = "vish")
if db.is_connected():
print("success")
a = int(input("roll no. : "))
b = input("name : ")
c = int(input("phone : "))
cursor = db.cursor()
q = ("insert into student values({}, '{}', {})".format(a,b,c))
cursor.execute(q)
db.commit()
how do i take date and insert it into a table
If you have a table t and a column c and you wish to insert a date literal, the format for that literal is 'YYYY-MM-DD', so for example:
INSERT INTO t(c) VALUES('2020-01-11')
But whenever you are getting input from the "outside", you are leaving yourself open to SQL Injection attacks and should be using prepared statements. If you have parsed the input date and built a string literal such as '2020-01-11' from the input, then you are safe. But if you have isolated the year, month and day and you are using a prepared statement anyway because there are other values you have not so rigorously validated, you can also use a '?' parameter for the date thus:
from datetime import date
today = date(2020, 1, 11)
cursor = db.cursor()
cursor.execute("INSERT INTO t(c) VALUES(?)", (today,))
cursor.commit()
I am writing a function that will retrieve data from sqlite table based on the parameters user provide. This is the function so far
def database_retrieve(db_file, id):
try:
conn = sqlite3.connect(db_file)
with conn:
sql_command = "SELECT * FROM my_table WHERE id = "+id
cur = conn.cursor()
cur.execute(sql_command)
result = cur.fetchall()
return result
except Exception as e:
print(e)
db_file = 'testdb.db'
print(database_retrieve(db_file, 'subject1'))
This gives me the following error
no such column: subject1
None
When I add subject1, which is an entry under the id column in my_table, directly to the sql command like this
sql_command = "SELECT * FROM my_table WHERE id = 'subject1'"
it works fine and prints all the data.
I am new to sqlite3. Please help. Thanks in advance
These are the links I used to come this far
Python sqlite3 string variable in execute
https://www.dummies.com/programming/databases/how-to-retrieve-data-from-specific-rows-in-mysql-databases/
When you do this
sql_command = "SELECT * FROM my_table WHERE id = "+id
The value of sql_command is
"SELECT * FROM my_table WHERE id = subject1"
As you can see, subject1 is not in quotes. sqlite thinks it is a column, that's why you see that error.
Instead, do this
sql_command = "SELECT * FROM my_table WHERE id = ?"
cur.execute(sql_command, [id])
? acts as a placeholder for the variable id.
The official sqlite3 documentation mentions few others methods
https://docs.python.org/2/library/sqlite3.html
The sql_command string being generated should be something like this (Formatted string):
sql_command = "SELECT * FROM my_table WHERE id = %s AND name = %s" % (212212, 'shashank')
I want to fetch all rows from MySQL table with
query = "SELECT * FROM %s WHERE last_name=%s"
cursor.execute(query, ("employees","Smith"))
but I'm getting
You have an error in your SQL syntax. When I try
query = "SELECT * FROM employees WHERE last_name=%s"
cursor.execute(query, ("Smith",))
all is fine.
Documentation says
cursor.execute(operation, params=None, multi=False)
The parameters found in the tuple or dictionary params are bound to the variables in the operation.link on docs
The first will generate an SQL like this:
SELECT * FROM 'employees' WHERE last_name='smith'
The parameters are SQL quoted.
If you really need to have a table name as param, you must proceed in 2 steps:
table_name = 'employees'
query_tpl = "SELECT * FROM {} WHERE last_name=%s"
query = query_tpl.format(table_name)
cursor.execute(query, ("Smith",))
you need to add the quote symbol. So the query will be like
SELECT * FROM employees WHERE last_name='Smith'
Change both your query to
query = "SELECT * FROM %s WHERE last_name='%s'"
query = "SELECT * FROM employees WHERE last_name='%s'"
You can't use a parameter for the table name in the execute call.
But you can use Python string interpolation for that:
query = "SELECT * FROM %s WHERE last_name=%s" %("employees","Smith")
cursor.execute(query)
You can't use a table name as a parameter. you are generating invalid sql with your code that is putting quotes around each string. the table name cannot have quotes around it.
sql you are generating
select * from 'employees' where last_name = 'Smith'
What sql you want
select * from employees where last_name = 'Smith'
you would have to format the string first like the example below.
query = "SELECT * from {} wherre last_name ='{}'"
cursor.execute(query.format("employees","Smith"))
using code like this does open up the possibility of SQL injection. so please bear that in mind.
query="SELECT * FROM %s WHERE name=%s",(employees,smith)
cursor.execute(query)
rows = cursor.fetchall()
Try this one. Hopefully it works for you.