Python - MySQL "Column count doesn't match value count at row 1" - python

name = form.name.data
email = form.email.data
username = form.username.data
password = sha256_crypt.encrypt(form.password.data)
cursor = mysql.connection.cursor()
cursor.execute("Insert into users(name,email.username,password) values(%s,%s,%s,%s)",(name,email,username,password))
mysql.connection.commit()
cursor.close()
I am using python with mysql to send the data entered in the table from a table in the database but I am getting such an error. Can you help me?

cursor.execute("Insert into users(name,email.username,password)
You have a "." instead of a "," between email and username. It should be
cursor.execute("Insert into users(name,email,username,password)

Related

Why does the searching of an item in my sqlite table, using python, only work when the data is a number saved as text?

I'm trying to create a contact book as a personal project. In the 'find_contact()' function, when I use the 'emaiL' variable to perform a query, it error message says that the data (I pre-recorded in the table) doesn't exist. But when I changed the variable to be used to query to 'phoneNum' (which is a number in text form) the query worked. How do I go about this please?
import sqlite3
conn = sqlite3.connect('contactBook.db')
cur = conn.cursor()
records = cur.fetchall()
#create table
cur.execute("""CREATE TABLE IF NOT EXISTS contacts (
first_name TEXT NOT NULL,
last_name TEXT,
phone_number TEXT NOT NULL PRIMARY KEY,
email,
address TEXT,
UNIQUE(phone_number, email)
)""")
#conn.close()
def save_contact():
save_contact.firstName = input("First name of contact: ")
lastName = input("Last name of contact: ")
phoneNumber = input("Phone number of contact: ")
email_ = input("Email of contact: ")
address_ = input("Address of contact: ")
cur.execute("INSERT OR IGNORE INTO contacts (first_name, last_name,phone_number,
email,address) VALUES (?, ?, ?, ?, ?)",
(save_contact.firstName, lastName, phoneNumber, email_, address_))
conn.commit()
def find_contact():
emaiL = input('Enter email: ')
query = f'''SELECT * FROM contacts WHERE email = {emaiL}'''
lua = f'''SELECT first_name, phone_number FROM contacts WHERE email = {emaiL}'''
#cur.execute("SELECT * FROM contacts (email) VALUES (?)", (email,))
cur.execute(query)
#conn.commit()
print(cur.execute(lua))
req = input("Hello, would you like to save or search for a contact: ")
if str.lower(req) == 'save':
save_contact()
x = save_contact.firstName
print("You have successfully saved " + x + "'s details")
elif str.lower(req) == 'search':
find_contact()
The test run was:
Hello, would you like to save, search or update for a contact:
search
Enter email: mine
The traceback:
Traceback (most recent call last):
File "c:\Users\GLORIA\Desktop\MINE\db.py", line 60, in <module>
find_contact()
File "c:\Users\GLORIA\Desktop\MINE\db.py", line 33, in
find_contact
cur.execute(query)
sqlite3.OperationalError: no such column: mine
query = f'''SELECT * FROM contacts WHERE email = {emaiL}'''
If the value of the variable emaiL is the string 'mine', this creates the SQL statement
SELECT * FROM contacts WHERE email = mine
but in this statement, mine would be interpreted by SQLite as a column name. If you want it to be interpreted as a string, quotes would need to be added:
SELECT * FROM contacts WHERE email = "mine"
However, don't try to adjust the string formatting line, query = f'''...''' to add the quotes, instead use a parameterized statement with ? as a placeholder, like you did for the other SQL statements in your code.
query = 'SELECT * FROM contacts WHERE email = ?'
cur.execute(query, (emaiL,))
See How to use variables in SQL statement in Python? for reasons to do so.
In the query query = f'''SELECT * FROM contacts WHERE last_name = {emaiL}''' is it not supposed to be f'''SELECT * FROM contacts WHERE email = {emaiL}'''?
It's probably because your {emaiL} doesn't have quotes for the email in the query, like this:
f'''SELECT * FROM contacts WHERE email = '{emaiL}' '''
If you print out your current query variable, you'll get SELECT * FROM contacts WHERE email = mine, which isn't valid. You want to get the string SELECT * FROM contacts WHERE email = 'mine'.

Python MySQL Programming Error:1064(42000), while making form using Flask

I am trying to make a form using Flask and upload the data of form to MySQL database and there I am encountering this error.
1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1
I used the following code:
if request.method=="POST" and form.validate():
username=form.username.data
email=form.email.data
password=sha256_crypt.encrypt((str(form.password.data)))
c,conn=connections()
x = c.execute("SELECT * FROM users WHERE username = (%s)",
(thwart(username)))
if int(x) > 0:
flash("That username is already taken, please choose another")
return render_template('register.html', form=form)
else:
c.execute("INSERT INTO users (username, password, email, tracking) VALUES (%s, %s, %s, %s)",
(thwart(username), thwart(password), thwart(email), thwart("/introduction-to-python-programming/")))
conn.commit()
flash("Thanks for registering!")
c.close()
conn.close()
You aren't setting what %s is wrong, it should be like this
x = c.execute("SELECT * FROM users WHERE username = (%s)" %
(thwart(username)))
or
x = c.execute(f"SELECT * FROM users WHERE username = {thwart(username))}")
The problem is, that you have the %s in parentheses, the code it should look like this
x = c.execute(
"SELECT * FROM users WHERE username = %s",
(thwart(username),)
)
The , behind thwart(username)) is mandatory and tells Python you want that to be a tuple of size 1, otherwise it would be interpreted as a string.

SQLITE3 FROM table Select column WHERE Boolean statement

I have tried 3 different variations of sqlite3 statement to SELECT a data:
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
cursor.execute('''SELECT * FROM users WHERE username = ?;''', (username,))
cursor.execute('SELECT * FROM users WHERE username = "monkey1" ')
References for these statements are from 1 2. However, none of them worked. I suspect that I am doing something really silly but can't seem to figure this out.
I want to be able to print out the data of username "monkey". Appreciate any help to point out my silly mistake.
import sqlite3
import datetime
def get_user(connection, rows='all', username=None ):
"""Function to obtain data."""
#create cursor object from sqlite connection object
cursor = connection.cursor()
if rows == 'all':
print("\nrows == 'all'")
cursor.execute("SELECT * FROM users")
data = cursor.fetchall()
for row in data:
print(row)
if rows == 'one':
print("\nrows == 'one'")
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
#cursor.execute('''SELECT * FROM users WHERE username = ?;''', (username,))
#cursor.execute('SELECT * FROM users WHERE username = "monkey1" ')
data = cursor.fetchone()
print('data = ',data)
cursor.close()
return data
def main():
database = ":memory:"
table = """ CREATE TABLE IF NOT EXISTS users (
created_on TEXT NOT NULL UNIQUE,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL UNIQUE
); """
created_on = datetime.datetime.now()
username = 'monkey'
email = 'monkey#gmail'
created_on1 = datetime.datetime.now()
username1 = 'monkey1'
email1 = 'monkey1#gmail'
# create a database connection & cursor
conn = sqlite3.connect(database)
cursor = conn.cursor()
# Insert data
if conn is not None:
# create user table
cursor.execute(table)
cursor.execute('INSERT INTO users VALUES(?,?,?)',(
created_on, email, username))
cursor.execute('INSERT INTO users VALUES(?,?,?)',(
created_on1, email1, username1))
conn.commit()
cursor.close()
else:
print("Error! cannot create the database connection.")
# Select data
alldata = get_user(conn, rows='all')
userdata = get_user(conn, rows='one', username=username )
print('\nalldata = ', alldata)
print('\nuserdata = ', userdata)
conn.close()
main()
Your table definition has the fields in order created_on, username, email but you inserted your data as created_on, email, username. Therefore the username of the first row was 'monkey#gmail'.
A good way to avoid this kind of mistake is to specify the columns in the INSERT statement rather than relying on getting the order of the original table definition correct:
INSERT INTO users (created_on, email, username) VALUES (?,?,?)

Python: IF doesn't work in SQLITE3

When I create the DataBase CURRENT_users.db:
import sqlite3
conn = sqlite3.connect('CURRENT_users.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome TEXT NOT NULL,
email TEXT NOT NULL,
created_in DATE NOT NULL,
password TEXT NOT NULL
)
""")
print("Success! DATABASE created with success!")
conn.close()
import UserLoginUI_Part2_Tes
t1
And I insert the DATA:
import sqlite3
conn = sqlite3.connect("CURRENT_users.db")
cursor = conn.cursor()
cursor.execute("""
INSERT INTO users (id, nome, email, created_in, password)
VALUES (001, "Renatinho", "renato.lenon#Outlook.com", 2005-4-21, "Plugxyvj9");
""")
conn.commit()
print("A new user has been incremented! Now,have fun!!!")
conn.close()
import UserInterface
In "UserInterface", I type "Renatinho" (that's my NOME data),it seems like that "IF" doesn't work!!
import sqlite3
conn = sqlite3.connect("CURRENT_users.db")
cursor = conn.cursor()
user_INFO = cursor.execute(""" SELECT nome FROM users; """)
user_in_SCRIPT = str(input("Your credentials: USERNAME: \n>>>"))
logged_in = False;
if user_in_SCRIPT == user_INFO:
print("You are logged in! Enjoy your new account...")
logged_in = True;
else:
print("Error: Not a valid user or USERNAME!!")
conn.close()
And it ever shows me the ELSE "command block"..
Please,who can help me?
Thanks for everything...
PRINT OF THE ERROR:
You've called SQL SELECT but you need to fetch the data.
cursor.execute("SELECT nome FROM users")
user_INFO = cursor.fetchone()
This would return a tuple, so to get the string inside, take the zero index:
if user_in_SCRIPT == user_INFO[0]:
print("You are logged in! Enjoy your new account...")
logged_in = True
BTW, you're in Python, not JavaScript. You don't need to end statements with semicolons. :-)

(see the screenshot..edited now)could not insert data into MySQLdb using python-flask

I created a db table from terminal, and now i want to insert data to it using following code,sql_insert_reg statement which is used as sql insert command is same as that i use in terminal insert operations but using in python file does not insert data .I am learning use of mysql in flask,here's my code.This code does not give error but does nothing as i expect it to!
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'EmpData'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
class RegistrationForm(Form):
username = TextField('Username', [validators.Length(min=4, max=25)])
password = PasswordField('New Password', [
validators.Required(),
validators.EqualTo('confirm', message='Passwords must match')])
confirm = PasswordField('Repeat Password')
accept_tos = BooleanField('I accept the TOS', [validators.Required()])
#app.route('/register',methods=['GET','POST'])
def register():
form = RegistrationForm(request.form)
flash('login details')
session['tmp'] = 43
if request.method == 'POST' and form.validate():
username = form.username.data
password = form.password.data
sql_insert_reg = "INSERT INTO User(userName,password) VALUES(%s,%s)"
#flash(sql_insert_reg)
conn = mysql.connect()
cursor = mysql.get_db().cursor()
cursor.execute(sql_insert_reg,(username,password))
conn.commit()
return render_template('register.html',form=form)
this is the screenshot i uploaded below..please see the entries useId 2 then goes directly to 6 ..and i got to see this by altering the answer as suggested to me!!can anyone lookout the problem behind the scene!
Please help me!
This is what a typical INSERT statement looks like:
INSERT INTO table (column1,column2,column3) VALUES (value1,value2,value3);
Note that if your first column is auto-incremental (e.g. some sort of index), you can ommit that from the statement and just write it as follows:
INSERT INTO User (user_column, pass_column) VALUES ('foo', 'bar');
So... don't do this:
sql = "INSERT INTO Table VALUES(NULL,'%s','%s')"%(username,password)+";"
Do this instead:
sql = "INSERT INTO Table (col1, col2) VALUES (%s, %s)"
cursor.execute(sql, (value1, value2))
Why? Because that will sanitize your input and you don't end up registering Bobby Drop Table as a user.
If doing it that way doesn't do what you expect, please provide more detail on what is happening, what you're expecting and how you know that you don't have what you expect to see.
this could be your problem
ursor.execute(sql_insert_reg,(username,password))
looks like it should be
cursor.execute(sql_insert_reg,(username,password))
and if thats not it, i would just use sqlalchemy to generate the sql for you
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker,scoped_session
import sqlalchemy as sa
Model = declarative_base()
engine = sa.create_engine('mysql://DB_USERNAME:DB_PASSWORD#DB_HOST:DB_PORT/DB_NAME')
Session = scoped_session(sessionmaker(bind=engine))
db_session = Session()
class User(Model):
__tablename__ = 'users'
id = sq.Column(sq.Integer,primary_key=True)
username = sq.Column(sq.String(255),nullable=False,unique=True)
password = sq.Column(sq.Text,nullable=False)
then if you want to manipulate the data you can change this from above
username = form.username.data
password = form.password.data
sql_insert_reg = "INSERT INTO User(userName,password) VALUES(%s,%s)"
#flash(sql_insert_reg)
conn = mysql.connect()
cursor = mysql.get_db().cursor()
ursor.execute(sql_insert_reg,(username,password))
conn.commit()
to this
user = User(username=form.username.data,password=form.password.data)
db_session.add(user)
db_session.commit()
I changed some code and found that instead of using the above lines of code in mysql i got this magic!
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()

Categories

Resources