Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 months ago.
Improve this question
I can't seem to be able to see for myself, what when wrong in this line of codes, have been staring at it for the last 20 min but I can't seem to figure anything out.
here is the error:
Traceback (most recent call last):
File "C:\Users\usera\PycharmProjects\itptesting_2\itptesting\init_db.py", line 7, in <module>
connection.executescript(f.read()),
sqlite3.OperationalError: near ")": syntax error
and the fullcode:
import sqlite3
connection = sqlite3.connect('database.db')
with open('schema.sql') as f:
connection.executescript(f.read())
cur = connection.cursor()
cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)",
('First Post', 'Content for the first post')
)
cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)",
('Second Post', 'Content for the second post')
)
cur.execute("INSERT INTO users (fullname, email, password) VALUES (?, ?, ?)",
('UserA', 'user#demo.com', 'asdfghjkl')
)
cur.execute("INSERT INTO entries (stockname, partnum, company, quantity, uom, remarks) VALUES (?, ?, ?, ?, ?, ?)",
('Beer','Albee0001','RES','24','BTL','new stock for promotions ')
)
connection.commit()
connection.close()
and schema.sql
DROP TABLE IF EXISTS posts;
CREATE TABLE posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
title TEXT NOT NULL,
content TEXT NOT NULL
);
DROP TABLE IF EXISTS signup;
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
fullname TEXT NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL
);
DROP TABLE IF EXISTS entries;
CREATE TABLE entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stockname TEXT NOT NULL,
partnum TEXT NOT NULL,
company TEXT NOT NULL,
quantity INTEGER NOT NULL,
uom TEXT NOT NULL,
date_recorded NOT NULL DEFAULT CURRENT_TIMESTAMP,
remarks TEXT NULL,
FOREIGN KEY(id) REFERENCES users(id),
);
I had tried deleting the database.db file and regenerating it by run init_db.py but it still gave me the same error. What should I do?
You have a couple of problems, this is the correct syntax:
CREATE TABLE entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stockname TEXT NOT NULL,
partnum TEXT NOT NULL,
company TEXT NOT NULL,
quantity INTEGER NOT NULL,
uom TEXT NOT NULL,
date_recorded DATE NOT NULL DEFAULT (CURRENT_TIMESTAMP),
remarks TEXT,
FOREIGN KEY(id) REFERENCES users(id)
);
Related
Here is my table creation code:
CREATE TABLE `crypto_historical_price2` (
`Ticker` varchar(255) COLLATE latin1_bin NOT NULL,
`Timestamp` varchar(255) COLLATE latin1_bin NOT NULL,
`PerpetualPrice` double DEFAULT NULL,
`SpotPrice` double DEFAULT NULL,
`Source` varchar(255) COLLATE latin1_bin NOT NULL,
PRIMARY KEY (`Ticker`,`Timestamp`,`Source`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_bin
I'm updating stuff in batch with sql statements like the following
sql = "INSERT INTO crypto."+TABLE+"(Ticker,Timestamp,PerpetualPrice,SpotPrice,Source) VALUES %s;" % batchdata
where batchdata is just a string of data in "('SOL', '2022-11-03 02:01:00', '31.2725', '31.2875', 'FTX'),('SOL', '2022-11-03 02:02:00', '31.3075', '31.305', 'FTX')
Now my script runs for a bit of time successfully inserting data in to the table but then it barfs with the following errors:
error 1265 data truncated for column PerpetualPrice
and
Duplicate entry 'SOL-2022-11-02 11:00:00-FTX' for key 'primary'
I've tried to solve the second error with
sql = "INSERT INTO crypto.crypto_historical_price2(Ticker,Timestamp,PerpetualPrice,SpotPrice,Source) VALUES %s ON DUPLICATE KEY UPDATE Ticker = VALUES(Ticker), Timestamp = VALUES(Timestamp), PerpetualPrice = VALUES(PerpetualPrice), SpotPrice = VALUES(SpotPrice), Source = VALUES(Source);" % batchdata
and
sql = "INSERT INTO crypto.crypto_historical_price2(Ticker,Timestamp,PerpetualPrice,SpotPrice,Source) VALUES %s ON DUPLICATE KEY UPDATE Ticker = VALUES(Ticker),Timestamp = VALUES(Timestamp),Source = VALUES(Source);" % batchdata
The above 2 attempted remedy runs and doesn't throw an duplicate entry error but it doesn't update the table at all.
If I pause my script a couple of minutes and re-run, the error duplicate error goes away and it updates which even confuses me EVEN more lol.
Any ideas?
import sqlite3
con=sqlite3.connect("mydbmb")
con.execute('''CREATE TABLE IF NOT EXISTS LOGIN
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
ROLL INT NOT NULL,
photo BLOB NOT NULL,
phone INTEGER NOT NULL,
father TEXT NOT NULL,
PASS TEXT NOT NULL);''')
with open("7.jpg", 'rb') as file:
blobdata = file.read()
quer=f'''INSERT INTO LOGIN(NAME,ROLL,photo,phone,father,PASS) VALUES('ADMIN','000','{blobdata}','678642873','GHHGJH','ADMIN123')'''
con.execute(quer)
print("query executed succsessfully")
user_list()
con.close()
Using literal parameters values (i.e. putting the values in the query) is error prone and insecure (unless they are constant)
It is much better to use bound parameters :
quer = '''INSERT INTO LOGIN(NAME,ROLL,photo,phone,father,PASS) VALUES(?, ?, ?, ?, ?, ?)'''
con.execute(quer, ('ADMIN','000', blobdata,'678642873','GHHGJH','ADMIN123'))
print("query executed successfully")
I am trying to connecting and inserting a data from json to sqlite. But it sucks me
I have tried to move and avoiding white spaces and copmleting with the databases
conn=sqlite3.connect('rosterdb.sqlite')
cur=conn.cursor()
cur.execute(
'''
DROP TABLE IF EXISTS USER;
DROP TABLE IF EXISTS Course;
DROP TABLE IF EXISTS Member;
CREATE TABLE User (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Course (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE
);
CREATE TABLE Member (
user_id INTEGER,
course_id INTEGER,
role INTEGER,
PRIMARY KEY (user_id, course_id)
)
'''
)
fname=input('Enter file name')
if len(fname)<1:
fname=roster_data.json
str_data=open(fname).read()
json_data=json.loads(str_data)
for entry in json_data:
name=entry[0]
title=entry[1]
role=entry[2]
print(name,title,role)
cur.execute('''INSERT OR IGNORE INTO User (name)
VALUES ( ? )''', ( name, ) )
cur.execute('SELECT id FROM User WHERE name = ? ', (name, ))
user_id = cur.fetchone()[0]
cur.execute('''INSERT OR IGNORE INTO Course (title)
VALUES ( ? )''', ( title, ) )
cur.execute('SELECT id FROM Course WHERE title = ? ', (title, ))
course_id = cur.fetchone()[0]
cur.execute('''INSERT OR IGNORE INTO Member(user_id,course_id,role)
VALUES(?,?,?)''',(user_id,course_id,role))
conn.commit()
File "roster.py", line 51
cur.execute('''INSERT OR IGNORE INTO Member(user_id,course_id,role)
^
IndentationError: unindent does not match any outer indentation level
You are probably mixing tabs and spaces
copy this to your editor:
cur.execute('''INSERT OR IGNORE INTO Member(user_id,course_id,role)
VALUES(?,?,?)''',(user_id,course_id,role))
And manually press space bar 4 times before cur.execute
And manually press space bar 8 times before VALUES
cur.execute('''INSERT OR IGNORE INTO Member(user_id,course_id,role)
VALUES(?,?,?)''',(user_id,course_id,role))
Please don't use tabs in combination with spaces
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to make a stock program for my neighborhood and, I am trying to run this code:
def create_tables():
c.execute('CREATE TABLE IF NOT EXISTS products(cod INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, bar_code INTEGER, '\
'descr VARCHAR(100) NOT NULL, quant_stock REAL, type_un TEXT, cost_un REAL, value_un REAL NOT NULL, fab_date TEXT, '\
'due_date TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS sells(cod INTEGER NOT NULL, bar_code INTEGER, '\
'descr TEXT PRIMARY KEY NOT NULL, value_un REAL NOT NULL, type_un TEXT, quant_stock REAL NOT NULL, '\
'tot_value REAL NOT NULL, sell_date TEXT NOT NULL, FOREIGN KEY (cod) REFERENCES products(cod)')
c.execute('CREATE TABLE IF NOT EXISTS purchase(cod INTEGER FOREIGN KEY, bar_code INTEGER, '\
'descr TEXT NOT NULL, cost_un REAL, type_un TEXT, pur_quant REAL NOT NULL, tot_cost REAL NOT NULL, '\
'pur_date TEXT NOT NULL, fab_date TEXT, due_date TEXT')
And I get this error:
File "app.py", line 17, in create_tables
c.execute('CREATE TABLE IF NOT EXISTS sells(cod INTEGER NOT NULL, bar_code INTEGER, '\
sqlite3.OperationalError: near ")": syntax error
I have no idea why this happens, because the first table is created with no problems (I already commented the two others and the script ran normally). Could anyone help me please?
You're missing a closing bracket in your second and third table inserts:
def create_tables():
c.execute('CREATE TABLE IF NOT EXISTS products(cod INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, bar_code INTEGER, '\
'descr VARCHAR(100) NOT NULL, quant_stock REAL, type_un TEXT, cost_un REAL, value_un REAL NOT NULL, fab_date TEXT, '\
'due_date TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS sells(cod INTEGER NOT NULL, bar_code INTEGER, '\
'descr TEXT PRIMARY KEY NOT NULL, value_un REAL NOT NULL, type_un TEXT, quant_stock REAL NOT NULL, '\
'tot_value REAL NOT NULL, sell_date TEXT NOT NULL, FOREIGN KEY (cod) REFERENCES products(cod))')
c.execute('CREATE TABLE IF NOT EXISTS purchase(cod INTEGER FOREIGN KEY, bar_code INTEGER, '\
'descr TEXT NOT NULL, cost_un REAL, type_un TEXT, pur_quant REAL NOT NULL, tot_cost REAL NOT NULL, '\
'pur_date TEXT NOT NULL, fab_date TEXT, due_date TEXT)')
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
This application will read roster data in JSON format, parse the file, and then produce an SQLite database that contains a User, Course, and Member table and populate the tables from the data file.
This code is incomplete as I need to modify the program to store the role column in the Member table to complete the problem. And I cannot understand how to do it.
import json
import sqlite3
conn = sqlite3.connect('rosterdb.sqlite')
cur = conn.cursor()
cur.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Member;
DROP TABLE IF EXISTS Course;
CREATE TABLE User (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Course (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE
);
CREATE TABLE Member (
user_id INTEGER,
course_id INTEGER,
role INTEGER,
PRIMARY KEY (user_id, course_id)
)
''')
fname = raw_input('Enter file name: ')
if ( len(fname) < 1 ) : fname = 'roster_data.json'
# [
# [ "Charley", "si110", 1 ],
# [ "Mea", "si110", 0 ],
str_data = open(fname).read()
json_data = json.loads(str_data)
for entry in json_data:
name = entry[0];
title = entry[1];
print name, title
cur.execute('''INSERT OR IGNORE INTO User (name)
VALUES ( ? )''', ( name, ) )
cur.execute('SELECT id FROM User WHERE name = ? ', (name, ))
user_id = cur.fetchone()[0]
cur.execute('''INSERT OR IGNORE INTO Course (title)
VALUES ( ? )''', ( title, ) )
cur.execute('SELECT id FROM Course WHERE title = ? ', (title, ))
course_id = cur.fetchone()[0]
cur.execute('''INSERT OR REPLACE INTO Member
(user_id, course_id) VALUES ( ?, ? )''',
( user_id, course_id ) )
conn.commit()
Once the necessary changes are made to the program and it has been run successfully reading the given JSON data, run the following SQL command:
SELECT hex(User.name || Course.title || Member.role ) AS X FROM
User JOIN Member JOIN Course
ON User.id = Member.user_id AND Member.course_id = Course.id
ORDER BY X
Find the first row in the resulting record set and enter the long string that looks like 53656C696E613333.
On one hand, there are two changes you need to make in your code:
name = entry[0];
title = entry[1];
role = entry[2];
print name, title, role
and
cur.execute('''INSERT OR REPLACE INTO Member
(user_id, course_id, role) VALUES ( ?, ?, ? )''',
( user_id, course_id, role ) )
but on the other hand, if you're having problems with your Coursera homework, you should really be posting to the class discussion forums about it (after reading what people have already posted about it there, in case that answers your questions) rather than to Stack Overflow. Considering that your question is about an assignment that was due some time ago rather than a current one, I don't feel so bad about talking about it here, but yeah, in the future use the discussion forums instead, and look at what I posted here to understand what is going on.