I can insert hardcoded values into an SQLite table with no problem, but I'm trying to do something like this:
name = input("Name: ")
phone = input("Phone number: ")
email = input("Email: ")
cur.execute("create table contacts (name, phone, email)")
cur.execute("insert into contacts (name, phone, email) values"), (name, phone, email)
I know this is wrong, and I can't find how to make it work. Maybe someone could point me in the right direction.
You can use ? to represent a parameter in an SQL query:
cur.execute("insert into contacts (name, phone, email) values (?, ?, ?)",
(name, phone, email))
cur.executemany("insert into contacts (name, phone, email) values (?, ?, ?)",
(name, phone, email))
cur.execute("create table contacts (name, phone, email)")
cur.execute("insert into contacts (name, phone, email) values(?,?,?)",(name, phone, email))
OR
cur.execute("insert into contacts values(?,?,?)",(name, phone, email))
As you are inserting values to all available fields, its okay not to mention columns name in insert query
Related
I have two tables say Doctors and patients. I need to fetch the doctors id (unique) from the doctors table and then pass it to a column of the patient's table during the INSERT operation. How can I write the query for that.
I tried the below way but it gives programming error:
usr = self.current_user
self.db.execute("INSERT INTO patients ("SELECT id FROM doctors WHERE doctors.id = '%s' " % usr )(mrd, name, age, gender, address, phone_number, blood_group,\
registration_date, did) values ('%s', '%s', '%s', '%s','%s','%s','%s','%s', '%s')" % (mrd,name,age,gender,\
address,phoneNumber, bloodGroup,dateOfReg,usr),callback=self.add_response)
I am trying to execute this in python tornado framework with psql backend
SELECT should be in VALUES section
The query will be like so
doctor_id = self.db.execute("SELECT id FROM doctors WHERE doctors.id = '%s' " % usr ).fetchone()
self.db.execute("INSERT INTO patients(mrd, name, age, gender, address, phone_number, blood_group,registration_date, did, doctor_id) values (%s, %s, %s, %s,%s,%s,%s,%s,%s, %s)" % (mrd,name,age,gender,address,phoneNumber, bloodGroup,dateOfReg,usr, doctor_id),callback=self.add_response)
The below program collects the users inputs and stores them, it then saves that data to a .csv / emails it to me and finally inserts that data into a MySQL database.
I am using mysql.connector for this, however I am getting the error:
AttributeError: 'tuple' object has no attribute 'encode'
when the program executes.
Here is the code, I think the problem is to do with the type of data trying to be inserted into the database, but I cannot be sure.
import mysql.connector
# ...
# Connect to MySQL Database and send user_input data to 'user' TABLE.
cnx = mysql.connector.connect(user='root', password='ash123', host='localhost', database='user_data_db')
cursor = cnx.cursor()
query = ("INSERT INTO user (user_id, first_name, last_name, age, postcode, email_address)"
"VALUES (%s, %s, %s, %s, %s, %s)", (user_id, firstname, lastname, age, postcode, email))
cursor.execute(query)
print("Executed Successfully")
cursor.close()
cnx.close()
Unless it's of the bytes or bytearray type, cursor.execute expects the first argument (SQL query) to have the encode method. query is a 2-tuple, tuples do not have that method and attempts to access it fail with AttributeError.
You can unpack query, in order to use its elements as positional arguments for cursor.execute:
cursor.execute(*query)
# = cursor.execute("INSERT INTO user (user_id, first_name, last_name, age, postcode, email_address)"
# "VALUES (%s, %s, %s, %s, %s, %s)", (user_id, firstname, lastname, age, postcode, email))
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.
in my database I'm using raw_input to allow users to enter data into a database, the problem is that I have an ID assigned to each record of data that is the primary key of the table.
username = raw_input("What would you like your username to be? ")
email = raw_input("What is your email address? ")
firstName = raw_input("What is your first name? ")
surname = raw_input("What is your surname? ")
age = raw_input("How old are you? ")
password = raw_input("What is your password?") #Encryption method will be added later
age = int(age) #Changing the age variable into an integer so it can be inputted into the database
#DB part
conn = db.connect('apollo.db') #Connecting to the database
cursor = conn.cursor()
cursor.execute("INSERT INTO users VALUES(?, ?, ?, ?, ?, ?)",
(username, email, firstName, surname, age, password)) #Inserting the user's data into the table
conn.commit() #Committing the changes
conn.close() #Closing the connection
I assumed that because the primary key increments automatically that it would not be needed to be added into the code because each record would automatically get a number. The problem is, I get this error message when I've answered all of the raw_input questions:
sqlite3.OperationalError: table users has 7 columns but 6 values were supplied
Is there something I need to add to the code for the primary key?
I guess the problem is this:
cursor.execute("INSERT INTO users VALUES(?, ?, ?, ?, ?, ?)",
Try this exchange of that:
cursor.execute("INSERT INTO users (username, email, firstName, surname, age, password) VALUES ",
(username, email, firstName, surname, age, password))
and i think this link can explain it more for you my friend.
I have a simple registration form which creates a new record in "Students" table:
cur = con.cursor()
query = "INSERT INTO students (Name, Address, Major, Phone, Email, Password) values (%s, %s, %s, %s, %s, %s)"
args = [name, address, major,phone, email, password]
cur.execute(query, args)
con.commit()
The column Id is auto-incremented, so in order to get the last Id, I select Max
query = "SELECT MAX(Id) FROM students;"
cur.execute(query)
id = cur.fetchone()[0]
It works in my little homework-project, but how would it be done in a heavy-loaded project, where there is a possibility of something being created before the select statement?
Use lastrowid attribute:
...
cur.execute(query, args)
id = cur.lastrowid