This question already has answers here:
Is there a way to get a list of column names in sqlite?
(13 answers)
Closed 6 years ago.
I have a short question for one of my classes; it involves building a function in python that takes a sqlite database name and a table name as arguments, and returns the column names inside this table.
So far I have done the following:
#!/user/bin/env python
import sqlite3
import pprint
pp = pprint.PrettyPrinter()
def print_table_columns(database_name, table_name):
conn = sqlite3.connect(database_name)
c = conn.cursor()
c.execute('SELECT sql FROM sqlite_master WHERE type=\'table\' AND name=\'table_name\'')
print c.fetchall()
conn.close()
Sadly, this code produces an empty list. I suspect that the SQL command inside the execute function does not take variables defined in Python, but I am not sure. Any help on this would be much appreciated.
Sure, you need to parameterize the query:
c.execute("""
SELECT
sql
FROM
sqlite_master
WHERE
type = 'table' AND
name = ?""", (table_name, ))
where ? is a placeholder that sqlite3 would fill with the query parameter (table_name here).
Related
This question already has answers here:
SQLite not saving data between uses
(1 answer)
python sqlite3, how often do I have to commit?
(1 answer)
Closed 1 year ago.
I have a database in python sqlite3 and I'm trying to delete rows from it depending on a value that I selected.
After the execution of this code, I got the result that I want when I'm in this function. But the problem is that when I'm out of this function and try to print the database, the deletion query did not work but the one to add values did. Can anyone understand why?
def datamanip():
selected = SecTree.focus()
values = SecTree.item(selected, 'text')
conn = sqlite3.connect('DataStore.db')
c = conn.cursor()
query='DELETE FROM Limits WHERE TypeCard=(?)'
c.execute(query,(values,))
c.execute("INSERT INTO Limits VALUES (:TypeCard,:CreaseMaxC,:CreaseMinC,:CreaseMaxA,:CreaseMinA,:WidthMaxC,:WidthMinC,:WidthMaxA,:WidthMinA)",
{'TypeCard':values,
'CreaseMaxC': w2data,
'CreaseMinC': wdata,
'CreaseMaxA': w4data,
'CreaseMinA': w3data,
'WidthMaxC': w6data,
'WidthMinC': w5data,
'WidthMaxA': w8data,
'WidthMinA': w7data
}
)
c.execute('SELECT * FROM Limits')
records= c.fetchall()
print(records)
EDIT:
The connection must be commited after making the deletion for the database.
conn.commit()
solved the problem.
This question already has answers here:
Python SQLite how to get SQL string statement being executed
(4 answers)
Closed 2 years ago.
Here I see the suggested way of building queries with python and sqlite3:
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print(c.fetchone())
How do I print the query instead of the result? I know it's not a string, and so a "print sql" statement wouldn't work. In my case, I am running flask and I want to have this code responding to an API invocation:
...
cur = conn.cursor()
arguments = (username, password, )
query = 'SELECT * FROM logins where ((username = ?) AND (password = ?));', arguments
return(query)
...
I would expect to see this query, not to execute it. However, I receive this output:
ValueError: too many values to unpack (expected 2)
Furthermore, I didn't see any method that exports the last query issued in the SQLite.
This might not be the answer you're looking for, but you can format the query as a string using python string format and print, before formatting again using db-api within the c.execute() statement. As long as you only format the executed query with db-api, you're not at risk from sql injection.
This question already has answers here:
List of tables, db schema, dump etc using the Python sqlite3 API
(12 answers)
Closed 7 years ago.
I have a problem to get data from the sqlite3 database. I can't find out the names of tables and their encoding. When I open DB through sqlitebrowser names were just unreadable characters.
Connection to DB is fine.
conn = sqlite3.connect('my.db')
conn_cursor = conn.cursor()
conn.text_factory = str
But how can I get the names of tables and their encoding?
You can use this query to get tables names.
res = conn.execute("SELECT name FROM sqlite_master WHERE type='table';")
for name in res.fetchall():
print(name[0])
This question already has answers here:
Database does not update automatically with MySQL and Python
(6 answers)
Closed 7 years ago.
In MySQL I have create db with name "test" and one table with name "table". Table have one column name: "A" and set as datatype INT(1).
In Python I have this code:
import MySQLdb
db = MySQLdb.connect(host="localhost",
user="root",
db="test")
cur = db.cursor()
myList = [1,2,3,4]
for row in myList:
print row
cur.execute("INSERT INTO table (a) VALUES (%s)" % row)
Goal from code above is after loop is finish my table "table" shoud have data like this:
|A|
|1|
|2|
|3|
|4|
But my table is empty after refresing. So my question is how to insert into table from loop in Python
Tnx
You did not commit your transaction. Try adding db.commit() after the loop.
You can use db.commit () after your data is loaded or set db.autocommit(True) beforehand.
This question already has answers here:
imploding a list for use in a python MySQLDB IN clause
(8 answers)
Closed 1 year ago.
I want to insert a list in my database but I can't.
Here is an example of what I need:
variable_1 = "HELLO"
variable_2 = "ADIOS"
list = [variable_1,variable_2]
INSERT INTO table VALUES ('%s') % list
Can something like this be done? Can I insert a list as a value?
When I try it, an error says that is because of an error in MySQL syntax
The answer to your original question is: No, you can't insert a list like that.
However, with some tweaking, you could make that code work by using %r and passing in a tuple:
variable_1 = "HELLO"
variable_2 = "ADIOS"
varlist = [variable_1, variable_2]
print "INSERT INTO table VALUES %r;" % (tuple(varlist),)
Unfortunately, that style of variable insertion leaves your code vulnerable to SQL injection attacks.
Instead, we recommend using Python's DB API and building a customized query string with multiple question marks for the data to be inserted:
variable_1 = "HELLO"
variable_2 = "ADIOS"
varlist = [variable_1,variable_2]
var_string = ', '.join('?' * len(varlist))
query_string = 'INSERT INTO table VALUES (%s);' % var_string
cursor.execute(query_string, varlist)
The example at the beginning of the SQLite3 docs shows how to pass arguments using the question marks and it explains why they are necessary (essentially, it assures correct quoting of your variables).
Your question is not clear.
Do you want to insert the list as a comma-delimited text string into a single column in the database? Or do you want to insert each element into a separate column? Either is possible, but the technique is different.
Insert comma-delimited list into one column:
conn.execute('INSERT INTO table (ColName) VALUES (?);', [','.join(list)])
Insert into separate columns:
params = ['?' for item in list]
sql = 'INSERT INTO table (Col1, Col2. . .) VALUES (%s);' % ','.join(params)
conn.execute(sql, list)
both assuming you have established a connection name conn.
A few other suggestions:
Try to avoid INSERT statements that do not list the names and order of the columns you're inserting into. That kind of statement leads to very fragile code; it breaks if you add, delete, or move columns around in your table.
If you're inserting a comma-separted list into a single-field, that generally violates principals of database design and you should use a separate table with one value per record.
If you're inserting into separate fields and they have names like Word1 and Word2, that is likewise an indication that you should be using a separate table instead.
Never use direct string substitution to create SQL statements. It will break if one of the values is, for example o'clock. It also opens you to attacks by people using SQL injection techniques.
You can use json.dumps to convert a list to json and write the json to db.
For example:
insert table example_table(column_name) values(json.dumps(your_list))