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.
Related
This question already has answers here:
Sqlite insert query not working with python?
(2 answers)
Closed 1 year ago.
I am currently learning SQL for one of my projects and the site, that I learn from, advised me to use DB Browser to see my Database Content. However, I can't see the data inside the SQL. This is how my code looks like. I'm creating a table and then trying to write some values in it. It creates the DB successfully but the data doesn't show up.
import sqlite3 as sql
connection = sql.connect("points.db")
cursor = connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS servers (server_id TEXT, name TEXT, exp INTEGER)")
cursor.execute("INSERT INTO servers VALUES ('848117357214040104', 'brknarsy', 20)")
Can you check that your data is inserted?
Something like this in the end:
cursor.execute("SELECT * FROM servers")
r = cursor.fetchall()
for i in r:
print(r)
Perhaps SQLite browser just needs a refresh
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:
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).
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:
Python MySQLDB: Get the result of fetchall in a list
(7 answers)
Closed 7 years ago.
I'm running a PostGreSQL query and when I print it, this is returned: [{'sum': 117L}]
Here is the code itself:
cursor.execute("SELECT SUM(length) FROM carmileage")
totalLength = cursor.fetchall()
print totalLength
How would I format this into a number without the (what appears to be) surrounding JSON?
Simply iterate through your resultset. Cursors pass rows in SQL select queries into Python lists:
cursor.execute("SELECT SUM(length) FROM carmileage")
totalLength = cursor.fetchall()
for row in totalLength:
print(row)