I'm writing a python-program that is supposed to enter some data into a database. This does not work. Here's the code:
dbcon = lite.connect('spcbase.db') # Connects to database file spcbase.db.
print "Connected to database"
cur=dbcon.cursor() # Creates database cursor.
print "Cursor defined"
cur.execute("CREATE TABLE IF NOT EXISTS spectrum(spectrumID INTEGER PRIMARY KEY AUTOINCREMENT, seriesID INTEGER, scan_ang DECIMAL, Path TEXT)")
cur.execute("CREATE TABLE IF NOT EXISTS series(seriesID INTEGER PRIMARY KEY AUTOINCREMENT, date DATE, gpsx DECIMAL, gpsy DECIMAL, colprec DECIMAL, refangle DECIMAL)")
# Executes SQL-query that will create one table of spectrums
# and one table over series of measurements, should these
# tables or this database not exist.
cur.execute("INSERT INTO series(date, gpsx, gpsy, colprec, refangle) VALUES(CURRENT_DATE, ?, ?, ?, ?)", [AP[0], AP[1], 6, refangle])
dbcon.commit()
cur.execute("SELECT MAX(seriesID) FROM series")
dbcon.commit()
current_series = cur.fetchone()[0]
src = u'.\\MaestroData'
print src
dest = u'.\\target'
print dest
files=getspc(src)
i=0
for mfile in files:
oldpath=os.path.normpath(os.path.join(src,mfile))
print "oldpath: ", oldpath
newpath=os.path.normpath(os.path.join(dest,mfile))
print "newpath", newpath
try:
os.rename(oldpath,newpath)
except:
print "File not moved."
cur.execute("INSERT INTO spectrum(seriesID, scan_ang, Path) VALUES (?, ?, ?)", [current_series, scan_dirs[i], newpath])
dbcon.commit()
i=i+1
(This is not the entire program, only the database handling part.) When this is run a file called spcbase.db is created. It has size 0 and contains nothing. Where does it go wrong?
Related
I have a table "Users" with the column "g_score". The other column I am storing are "username". I am trying to send an update to g_score via the username I get. I send the request and the value does not update. g_score is stored as an INT. I am looking to increment the value by + 1 each time.
The g_score value is default = 0
The value is not being updated by the following code
I'm going to leave some snippets here-
Creating the table -
cursor.execute("CREATE TABLE IF NOT EXISTS Users(username TEXT,hash TEXT,salt TEXT,g_score INT)")
If the user does not exist- we do
cursor.execute("INSERT INTO Users VALUES(?, ?, ?, ?)", (username, hashed_password, salt, 0))
This following code does not update the g_score-
db = lite.connect('log.db', check_same_thread=False)
cursor = db.cursor()
sql = ("UPDATE Users SET g_score = g_score + 1 WHERE username = ?")
cursor.execute(sql, [g_winner.get_name()])
I am getting the error 'sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 4, and there are 1 supplied.' The below code should be making a database and creating a table with the the titles listed below. Then take values from a csv. file and add it under the allotted headings. Any help would be would be appreciated!
import const
import sqlite3
SEP = ','
DATA_FILENAME = 'pokemon.csv'
con = sqlite3.connect('poki.db')
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS poki')
cur.execute( ' CREATE TABLE poki( pokemon TEXT, species_id INTEGER,'
' height REAL, weight REAL)' )
values = ('INSERT INTO poki VALUES (?, ?, ?, ?)')
for line in DATA_FILENAME:
list_of_values = line.strip().split(SEP)
cur.execute(values, list_of_values)
cur.close()
con.commit()
con.close()
having trouble with these two functions
was wondering if people could tell me where I am going wrong
this is a separate function as part of a spider that searches through a website of house prices
def save_house_to_db(id, address, postcode, bedrooms):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
d.execute('INSERT INTO TABLE houses (id, address, postcode, bedrooms) VALUES (%d %s %s %d)' %(id, str(address), str(postcode), float(bedrooms)))
d.commit()
d.close()
def save_transactions_to_db(id, sale_price, date):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
d.execute('INSERT INTO TABLE transactions (transaction_id NOT NULL AUTO_INCREMENT, house_id, date, sale_price) VALUES'
'(%d %s %s)' %(id, sale_price, str(date)))
d.commit()
d.close()
here is the error raised:
Traceback (most recent call last):
File "/Users/saminahbab/Documents/House_Prices/final_spider.py", line 186, in <module>
final_function(link_set=areas,id_counter=40)
File "/Users/s/Documents/House_Prices/final_spider.py", line 158, in final_function
page_stripper(link=(root+page), id_counter=id_counter)
File "/Users/s/Documents/House_Prices/final_spider.py", line 79, in page_stripper
save_house_to_db(id=float(id_counter), address=address, postcode=postcode, bedrooms=bedrooms)
File "/Users/s/Documents/House_Prices/final_spider.py", line 25, in save_house_to_db
d.execute('INSERT INTO TABLE houses VALUES (%d %s %s %d)' %(id, str(address), str(postcode), float(bedrooms)))
sqlite3.OperationalError: near "TABLE": syntax error
and for reference here is the execute for the databse
# conn = sqlite3.connect('houses_in_london.db')
# database = conn.cursor()
# database.execute('CREATE TABLE houses (id INTEGER PRIMARY KEY, address TEXT,'
# 'postcode TEXT, bedrooms TEXT)')
#
# database.execute('CREATE TABLE transactions (transaction_id NOT NULL AUTO_INCREMENT, house_id INTEGER '
# ' REFERENCES houses(id), date TEXT, sale_price INTEGER )')
as always, thank you for the support
You have many issues:
INSERT-clause has no TABLE keyword
You're trying to pass variables to an SQL query using string formatting; don't do it, ever – use placeholders, or face the consequences
Your VALUES-clause is missing commas between the value-expressions
The sqlite3 module uses "?" as a placeholder instead of percent formatters
"transaction_id NOT NULL AUTO_INCREMENT" is not a valid column name
"AUTO_INCREMENT" is not valid SQLite syntax and you probably meant for transaction_id to be INTEGER PRIMARY KEY – also AUTOINCREMENT should usually not be used
The below functions fix some of the errors, barring the DDL-corrections to the transactions table.
def save_house_to_db(id, address, postcode, bedrooms):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
# Remove the TABLE "keyword"
d.execute('INSERT INTO houses (id, address, postcode, bedrooms) '
'VALUES (?, ?, ?, ?)', (id, address, postcode, bedrooms))
d.commit()
d.close()
def save_transactions_to_db(id, sale_price, date):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
# This here expects that you've fixed the table definition as well
d.execute('INSERT INTO transactions (house_id, date, sale_price) '
'VALUES (?, ?, ?)', (id, sale_price, date))
d.commit()
d.close()
I wrote a program in order to dynamically update a database table but I am getting an error. I stuffed the program with whatever I know little about. Here's my code:
import MySQLdb
class data:
def __init__(self):
self.file123 = raw_input("Enter film: ")
self.title_ = raw_input("Enter film: ")
self.year = raw_input("Enter year: ")
self.director = raw_input("Enter director: ")
a=data()
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="mysql", # your password
db="sakila") # name of the data base
cursor = db.cursor()
cursor.execute("INSERT INTO films (file123, title_, year, director) VALUES (?, ?, ?, ?)", (a.file123, a.title_, a.year, a.director))
db.commit()
db.close()
This is the error:
File "C:\Python27\maybe1.py", line 20, in <module>
cursor.execute("INSERT INTO films (file123, title_, year, director) VALUES (?, ?, ?, ?)", (a.file123, a.title_, a.year, a.director))
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 184, in execute
query = query % db.literal(args)
TypeError: not all arguments converted during string formatting
How can I fix this issue ?
You should change ? to %s.
Here is question about why mysqldb use %s instead of ?.
I would do it this way:
query = "INSERT INTO films (file123, title_, year, director) VALUES (%s, %s, %s, %s)" % (a.file123, a.title_, a.year, a.director)
cursor.execute(query)
Replace %s with correct data type, else it will try everything as string which might break at table level.
Everytime I run this through the python interpreter it writes new values. for example:
name = ben
age = 10
phone = 42045042
If I run it 10 times. I get 10 duplicates in my database. I know it has to be an easy fix, but I've been working on this for hours and can't figure it out.
conn = sqlite3.connect('addressbook.db')
cur=conn.cursor()
conn.execute('''
CREATE TABLE IF NOT EXISTS people(name TEXT,
age TEXT, phone TEXT, fblink TEXT)''')
conn.execute("INSERT OR REPLACE INTO people values (?, ?, ?, ?)", ben.displayPerson())
cursor = conn.execute("SELECT name, age, phone, fblink from people")
for row in cursor:
print "NAME = ", row[0]
print "AGE = ", row[1]
print "PHONE = ", row[2]
print "FACEBOOK LINK = ", row[3], "\n"
cur.close()
conn.commit()
conn.close()
There's no primary key field.
Make a primary key field.
For example:
conn.execute('''
CREATE TABLE IF NOT EXISTS people(name TEXT primary key,
age TEXT, phone TEXT, fblink TEXT)''')
REPLACE is executed when UNIQUE constraint violation occurs. Without primary key (or unique ..), it does not happen.
Your table has no primary key, and hence SQLite doesn't know what it should "OR REPLACE" since it has nothing to base replacing on. Add a primary key.