I am trying to enter data into MySQL table using MySQLdb but it is not inserting data into table.
my code is :
try:
db = MySQLdb.Connect("127.0.0.1","root","root","bank")
cursor = db.cursor()
cursor.execute("SELECT max(account_number) from pybank")
results = cursor.fetchall()
for row in results:
self.account_number = row[0]
sql = "INSERT INTO pybank(account_number,user_name, user_age, user_dob, amount) VALUES(%d,'%s',%d,'%s',%d)" %(self.account_number + 1,self.user_name, self.user_age, self.user_dob, self.total_amount)
print(sql)
cr = db.cursor()
cr.execute(sql)
db.commit()
print("Your have successfully created your account")
self.getAccountDetails()
except:
db.rollback()
print("Your account is not created !!!! ")
print
print("Please try again")
You have mistype in SQL near VALUES, also you should use placeholders:
cursor = db.cursor()
cursor.execute("INSERT INTO pybank (account_number,user_name, user_age, user_dob, amount) VALUES (%s, %s, %s, %s, %s)", (self.account_number + 1, self.user_name, self.user_age, self.user_dob, self.total_amount))
Related
I working on a project and I want to use one database in two python file
but, when I run every project they created database for self
if you know please tell me how I can use that
import sqlite3
def connect():
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS salary (id INTEGER PRIMARY KEY , name text, age INTEGER , price INTEGER )"
)
conn.commit()
conn.close()
def insert(name, age, price):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"INSERT INTO salary VALUES (NULL ,?,?,?)", (name ,age ,price)
)
conn.commit()
conn.close()
def view():
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"SELECT * FROM salary"
)
rows = cur.fetchall()
conn.close()
return rows
def search(name="", age="", price=""):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"SELECT * FROM salary WHERE name = ? OR age = ? OR price = ?", (name, age, price)
)
rows = cur.fetchall()
conn.close()
return rows
def delete(id):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute("DELETE FROM salary WHERE id=?", (id,))
conn.commit()
conn.close()
def update(id, name, age, price):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"UPDATE salary SET name = ?, age = ?, price = ? WHERE id = ?", (name, age, price, id)
)
conn.commit()
conn.close()
def update_pay_money(name, price):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"UPDATE salary SET price = ? WHERE name = ?", (price, name)
)
conn.commit()
conn.close()
connect()
enter image description here
Giving exact path like /path/to/waiters.db while connecting to your database should solve your problem?
This line should be changed while connecting to database.
conn = sqlite3.connect("/path/to/waiters.db")
as Other mentioned for using a sqllite3 db in multiple files you can use their absolute or relative path, for example if you have 'DBs' & 'section-1' & 'section-2' directories and your python file are in section directories you can access the database file in each section by using somthing like this '"../DBs/waiters.db"' and so on for others... but whatf of you try make multiple tables in a database file in tgat way you don need to have multiple databases and its the standard way,
hope it's help
When I executing the following function, I get the following response:
Failed to insert data into sqlite table: no such table: users
user_id = uuid.uuid4()
save_record.name = name
save_record.score = score
last_time = datetime.now()
try:
conn = sqlite3.connect('OnlineJeopardy.db')
cursor = conn.cursor()
print("Successfully Connected to OnlineJeopardy DB.")
sqlite_insert_query = """INSERT INTO users
(User_id, Name, Score, Last_time)
VALUES
(?, ?, ?, ?)"""
add_to_db = cursor.execute(sqlite_insert_query, (user_id, name, score, last_time))
conn.commit()
cursor.close()
except sqlite3.Error as error:
print("Failed to insert data into sqlite table: ", error)
finally:
if (conn):
conn.close()
print("The SQLite connection is closed")
When I execute this query in DB Browser, with actual values instead of placeholders, it all goes well.
I've tried swapping placeholders to actual values (as below) within the query in sqlite3 but the outcome was the same.
conn = sqlite3.connect('OnlineJeopardy.db')
cursor = conn.cursor()
print("Successfully Connected to OnlineJeopardy DB.")
sqlite_insert_query = """INSERT INTO users
(User_id, Name, Score, Last_time)
VALUES
('ID-1337', 'Adam', 20, '2020-06-12 23:18:58')"""
add_to_db = cursor.execute(sqlite_insert_query)
conn.commit()
cursor.close()
I'm trying to:
Update the data so that marriage=2 (single) and marriage=3 (others) are merged into 2 (single).
and:
Remove all data records with negative BILL_AMT values (in any of the BILL_AMT1 through BILL_AMT6)
The issue is that I run the code, get the all clear message, check the database and nothing seems to have changed... #1 might be working but I can't figure out how to run it using all the rows and #2 nothing seems to have changed when I look back at the database:
import csv
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="hw6"
)
mycursor = mydb.cursor()
f = open("UCI_Credit_Card.csv")
for row in csv.reader(f):
a= row[0]
b= row[1]
c= row[2]
d= row[3]
e= row[4]
f= row[5]
g= row[6]
h= row[7]
i= row[8]
j= row[9]
k= row[10]
l= row[11]
m= row[12]
n= row[13]
o= row[14]
p= row[15]
q= row[16]
r= row[17]
s= row[18]
t= row[19]
u= row[20]
v= row[21]
w= row[22]
x= row[23]
y= row[24]
sql = "INSERT INTO customers (ID, LIMIT_BAL, SEX, EDUCATION, MARRIAGE, AGE, PAY_0, PAY_2, PAY_3, PAY_4, PAY_5, PAY_6, BILL_AMT1, BILL_AMT2, BILL_AMT3, BILL_AMT4, BILL_AMT5, BILL_AMT6, PAY_AMT1, PAY_AMT2, PAY_AMT3, PAY_AMT4, PAY_AMT5, PAY_AMT6, default_payment_next_month) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
val = (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
mycursor = mydb.cursor(buffered=True)
print("Before updating a record ")
sql_select_query = """select * from customers"""
mycursor.execute(sql_select_query)
record = mycursor.fetchone()
print(record)
# Update single record now
sql_update_query = """UPDATE CUSTOMERS SET SEX = 2 where SEX = 3"""
mycursor.execute(sql_update_query)
mydb.commit()
print("Record Updated successfully ")
print("After updating record ")
mycursor.execute(sql_select_query)
record = mycursor.fetchone()
print(record)
# Delete record now
mycursor = mydb.cursor(buffered=True)
sql_update_query = "DELETE FROM customers WHERE (BILL_AMT1<0)AND(BILL_AMT2<0)AND(BILL_AMT3<0)AND(BILL_AMT4<0)AND(BILL_AMT5<0)AND(BILL_AMT6<0) """
sql_delete_query = """select * from customers"""
mycursor.execute(sql_update_query)
mydb.commit()
print("Record Delete successfully ")```
The UPDATE statement looks fine.
But when it comes to the second requirement:
Remove all data records with negative BILL_AMT values (in any of the BILL_AMT1 through BILL_AMT6)
Presumably, you want ored conditions rather than and in the delete query:
DELETE FROM customers
WHERE
BILL_AMT1 < 0
OR BILL_AMT2 < 0
OR BILL_AMT3 < 0
OR BILL_AMT4 < 0
OR BILL_AMT5 < 0
OR BILL_AMT6 < 0
I have bad a python script that connects to a db gets information and then uses a few variables to input this information back into the db. I have tweaked the code until it runs with no errors but in the end it doesnt actually insert anything into the db. Here is the insert code i am using
company_name = input("what is the company name?: ")
host=("")
ts = time.time()
timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
#Start DB connection
conn = mysql.connector.connect (user=dbUser,password=dbPassword,host=host,buffered=True)
cursor = conn.cursor()
#Print Database Information
select_db = ("")
cursor.execute(select_db)
api_keys = ("select * from api_keys order by API_KEYS_ID desc limit 1")
cursor.execute(api_keys)
#print(api_keys)
#for (api_keys) in cursor:
# print(api_keys[0])
#api_key_id = api_keys[0] + 1
#print(api_key_id)
api_keys_id = 170
##
add_api_key = ("INSERT INTO api_keys(api_keys_id, api_key, status, email, ip_address, filter_query, create_date, description) \
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", (api_keys_id , api_token , 'A' , email , '*' , '(OwnerPartyID:' + ownerPartyID + ') AND (SalesStatus:' + salesStatus + ')' , timestamp , company_name + ' key'));
cursor.execute(*add_api_key)
conn.commit()
print(add_api_key)
I'm having a small problem with a Python program (below) that I'm writing.
I want to insert two values from a MySQL table into another table from a Python program.
The two fields are priority and product and I have selected them from the shop table and I want to insert them into the products table.
Can anyone help? Thanks a lot. Marc.
import MySQLdb
def checkOut():
db = MySQLdb.connect(host='localhost', user = 'root', passwd = '$$', db = 'fillmyfridge')
cursor = db.cursor(MySQLdb.cursors.DictCursor)
user_input = raw_input('please enter the product barcode that you are taking out of the fridge: \n')
cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1 where barcode = %s', (user_input))
db.commit()
cursor.execute('select product, priority from shop where barcode = %s', (user_input))
rows = cursor.fetchall()
cursor.execute('insert into products(product, barcode, priority) values (%s, %s)', (rows["product"], user_input, rows["priority"]))
db.commit()
print 'the following product has been removed from the fridge and needs to be ordered'
You don't mention what the problem is, but in the code you show this:
cursor.execute('insert into products(product, barcode, priority) values (%s, %s)', (rows["product"], user_input, rows["priority"]))
where your values clause only has two %s's in it, where it should have three:
cursor.execute('insert into products(product, barcode, priority) values (%s, %s, %s)', (rows["product"], user_input, rows["priority"]))
Well, the same thing again:
import MySQLdb
def checkOut():
db = MySQLdb.connect(host='localhost', user = 'root', passwd = '$$', db = 'fillmyfridge')
cursor = db.cursor(MySQLdb.cursors.DictCursor)
user_input = raw_input('please enter the product barcode that you are taking out of the fridge: \n')
cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1 where barcode = %s', (user_input))
db.commit()
cursor.execute('select product, priority from shop where barcode = %s', (user_input))
rows = cursor.fetchall()
Do you need fetchall()?? Barcode's are unique I guess and one barcode is to one product I guess. So, fetchone() is enough....isn't it??
In any case if you do a fetchall() its a result set not a single result.
So rows["product"] is not valid.
It has to be
for row in rows:
cursor.execute('insert into products(product, barcode, priority) values (%s, %s, %s)', (row["product"], user_input, row["priority"]))
db.commit()
print 'the following product has been removed from the fridge and needs to be ordered'
or better
import MySQLdb
def checkOut():
db = MySQLdb.connect(host='localhost', user = 'root', passwd = '$$', db = 'fillmyfridge')
cursor = db.cursor(MySQLdb.cursors.DictCursor)
user_input = raw_input('please enter the product barcode that you are taking out of the fridge: \n')
cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1 where barcode = %s', (user_input))
cursor.execute('insert into products(product, barcode, priority) select product, barcode, priority from shop where barcode = %s', (user_input))
db.commit()
Edit: Also, you use db.commit() almost like print - anywhere, you need to read and understand the atomicity principle for databases