Primary Key issues when using raw_input with SQLite 3 and Python - python

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.

Related

Failed to insert user input into MySQL database

I have created a database and inserted some value using python manual code but when i tried to taking input from user then inserting that input to my database table,i failed as i tried many ways.
Here is my code
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="Adee11ruchi#",
database="hdatabase"
)
mycursor = mydb.cursor()
name= str(input("What is your first name? "))
address=str(input("enter address:"))
#mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
mycursor.execute = ("""INSERT INTO customers (name, address) VALUES (r{}, r{})""".format(name, address))
#val = ('Peter', 'Lowstreet 4')
mydb.commit()
print(mycursor.rowcount, "record inserted.")
It showing me as
What is your first name? diyu
enter address:hiouy
-1 record inserted.
What is the issue,i failed to find out.
You should be using a prepared statement here. Consider this version:
mycursor = mydb.cursor(prepared=True)
name = input("What is your first name? ")
address = input("enter address:")
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
mycursor.execute = (sql, (name, address,))
mydb.commit()
The main takeaways points here are that you leave the values to be bound as parameters %s, and then you bind the values as a tuple in the call to cursor#execute. Note that the prepared statement API will handle the proper formatting of the inputs for you.

Error while trying to insert rsa key (tuple) into sql database

I am learning sqlite3 and I tried inserting an rsa key into one of my columns that I made but I get this error:
sqlite3.InterfaceError: Error binding parameter 2 - probably unsupported type.
Here's my code:
import sqlite3, rsa
db = sqlite3.connect('database.db')
db.execute('drop table if exists user')
db.execute('create table user (username text, password text, pubKey tuple,
privKey tuple)')
username = input("Input Username: ")
password = input("Input Password: ")
confirm = input("Confirm Password: ")
(pubKey, privKey) = rsa.newkeys(512)
if password == confirm:
db.execute('insert into user (username, password, pubKey, privKey) values (?, ?, ?, ?)', (username, password, pubKey, privKey))
db.commit()
else:
quit()
I am using rsa.newkeys to generate the keys and they generate as tuples. For example the tuple will be something along the lines of:
PublicKey(7993225774562669856453147392958346571937702133919317490212017912216372852796080413531673713173968180340315460310318908937895213458133041784535151317298739, 65537)
I looked at the documentation for rsa and rsa.newkeys() dpes return a tuple but I get the error saying it is the wrong data type.
pubKey and privKey are instances of the classes (rsa.key.PublicKey and rsa.key.PrivateKey)
From the instance you could take both vallues as int:
pubKey.n - from your example it's 7993225774562669856453147392958346571937702133919317490212017912216372852796080413531673713173968180340315460310318908937895213458133041784535151317298739
pubKey.e - it's 65537
If you need only the keys, save int to the db:
db.execute('create table user (username text, password text, pubKey int, privKey int)')
...
db.execute('insert into user (username, password, pubKey, privKey) values (?, ?, ?, ?)', (username, password, pubKey.n, privKey.n))
If you need a whole string, convert to str and save as text:
db.execute('create table user (username text, password text, pubKey text, privKey text)')
...
db.execute('insert into user (username, password, pubKey, privKey) values (?, ?, ?, ?)', (username, password, str(pubKey), str(privKey)))
Take a look at your RSA key - it's probably hex (i.e. there are numbers AND letters) so int will not work. Int is for numbers only.
I'd suggest either using text or blob for the type.

Get an automatic ID in the Python shell with SQlite

I need assistance with creating an automatic ID for the Employee's when the other information is inputted by the user, is anyone able to help? I don't want the Employee ID to be asked to be inputted by the user, I would like it to be automatically generated and inputted into that field. I also have to program it in python, I can't use a SQL program or anything. Feel free to change any parts of the code, it's pretty flimsy at the moment, I've been messing around with the 'rowid' code for a bit trying to get that to work and I can't figure it out, many thanks.
import sqlite3
def AddEmployee():
FirstName = input("Plaese enter the
employee's First Name: ")
LastName = input("Please enter the
employee's Last Name: ")
DName = input("Please Enter the employee's
Department Area: ")
Gender = input("Please enter the employee's
Gender: ")
Phone = int(input("Please enter the
employee's phone number: "))
Address1 = input("Please Enter the
employee's Address1: ")
Town = input("Please Enter the employee's
Town: ")
Postcode = input("Please Enter the
employee's Postcode: ")
DOB = input("Please Enter the employee's
Date of Birth: ")
HireDate = input("Please Enter the
employee's Date of Employment: ")
db = sqlite3.connect("Database.db")
cursor = db.cursor()
cursor.execute("INSERT INTO Employees
VALUES(rowid, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(EmployeeID, FirstName, LastName, DName,
Gender, Phone, Address1, Town, Postcode,
DOB, HireDate))
db.commit()
cursor.close()
db = sqlite3.connect("Database.db")
cursor = db.cursor()
cursor.execute("""CREATE TABLE IF NOT
EXISTS Employees
(EmployeeID integer PRIMARY KEY
AUTOINCREMENT, DName integer,
FirstName text, LastName text, Gender text,
Phone text,
Address1 text, Town text, Postcode text,
DOB Date,
HireDate Date)""")
cursor.execute("""CREATE TABLE IF NOT
EXISTS Salaries
(SalaryID integer PRIMARY KEY
AUTOINCREMENT, EmployeeID integer,
DepartmentDI integer, RegisterID integer,
FirstName text,
LastName text, Address1 text, Town text,
Postcode text, DOB Date,
HireDate Date, SalaryAmount integer,
DhourlyRate integer,
DOvertimeHourlyRate integer)""")
cursor.execute("""CREATE TABLE IF NOT
EXISTS Register
(RegisterID integer PRIMARY KEY
AUTOINCREMENT, EmployeeID integer,
Date Date, Time Time, Present Boolean,
HoursWorked integer,
OvertimeWorked integer)""")
cursor.execute("""CREATE TABLE IF NOT
EXISTS Departments
(DepartmentID integer PRIMARY KEY
AUTOINCREMENT, DName text, DQuota integer,
DHourlyRate integer, DovertimeHourlyRate
integer)""")
db.commit()
cursor.close()
AddEmployee()
you can do this
id = odm.SymbolField(primary_key=True)
If you dont have a field with a Primary Key than python create it automaticly.

python dynamic input, update table

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.

python + sqlite, insert data from variables into table

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

Categories

Resources