I have a mysql database in which 'user' table having f_name,l_name,password email(pk) by which session is created and table 'friendgroup' having fg_name(pk), email((pk),users.email(FK)) and table 'member' having email(pk,user.email(fk)), owner_email(pk,friendgroup.email(fk)), fg_name(pk,friendgroup.fg_name(fk)), and a python flask file below.
After login account, I wish to add a friend in chat. I tried to fix it from session['email']
def add_friend():
user = session['email']
friendgroups = _get_own_friendgroups(user) return
render_template('addFriend.html', friendgroups=friendgroups)
def _get_own_friendgroups(user):
cursor = mysql.connection.cursor()
#find all friendgroups that the user owns
find_owned_friendgroups = 'SELECT fg_name, description FROM friendgroup WHERE owner_email = %s ORDER BY fg_name ASC'
cursor.execute(find_owned_friendgroups, (user))
owned_friendgroups = cursor.fetchall()
cursor.close()
return owned_friendgroups
I expect output will be an open window and actively use of add friend when needed but showing error:
MySQLdb._exceptions.ProgrammingError: not all arguments converted during bytes formatting
A common error in python is to use (bar) instead of (bar,) the former not being a tuple.
Try with:
cursor.execute(find_owned_friendgroups, (user,))
Related
This is my current code
email = request.args.get('email')
password = request.args.get('password')
sql = 'SELECT email, senha FROM usuarios WHERE email = ?'
stmt = ibm_db.prepare(conn, sql)
param = email
email = ibm_db.fetch_assoc(stmt, param)
print(email)
It always returns an error and I can't get the values I need from my db2 database. What should I do to make it work?
my error code is
line 29, in login
email = ibm_db.fetch_assoc(stmt)
Exception: Fetch Failure: [IBM][CLI Driver] CLI0125E Function sequence error. SQLSTATE=HY010 SQLCODE=-99999
The code in the question missed out required steps:
ibm_db.bind_param() to give a value to the parameter marker
ibm_db.execute() to execute the prepared statement with the bound value
When there is an unexpected sequence (for example a missing API, in this case a fetch before any previous execute) then the driver will return CLI0125E (function sequence error).
Example code is in the Db2 documentation and many other places online.
It is wise to use exception handlers ( a try: ... except: block) in the code to catch and handle errors.
I am looking for your help because i am getting this error on Python Flask:
pymysql.err.ProgrammingError: (1064, "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 'Autoevaluacion', 'RT_Funcionarios', 'Reporteadores', 'Reporteadores_Gerentes', '' at line 1")
I am inserting data from Angular in my MySQL DB with the help of Flask, i am trying to insert the fields name, email, role and foros, this last one is filled with the elements of an array so when i tried to save the data, that error is shown.
this is my python code
#app.route('/insertarUsuario', methods = ["POST"])
def insertar_usuario():
conection = pymysql.connect('localhost', 'root','root', 'users')
data = request.json
print(data)
print(data['foros'])
cursor = conection.cursor()
sql_query ="INSERT INTO administrador_usuarios(nombre, email, rol, foros) VALUES ('" + str(data["nombre"]) + "','"+ str(data["email"])+"','"+str(data["rol"])+"', '"+ str(data["foros"])+"')"
cursor.execute(sql_query)
conection.commit()
response = "OK"
print("respuesta:",response)
return jsonify(response)
I would like to highlight 2 things:
1-. that array that will fill the field foros, it comes from the number of foros you select through checkboxes, so if i just check one, the register is saved but if i checked more than one, it crashes.
2-. i found out that if i replace
(data["foros"])
for
str("autoevaluacion" + "rt_funcionario")
it works so i think maybe it about how do i receive the array.
Can you help me please?. I am kinda new on Flask
I am trying to create a local database of my email using Python.
I am using Imaplib to read email from Imap server. My target is to push the extracted emails to a local MySql database in the format "SUBJECT", "SENDER", "RECEIVER".
I have built up the code that creates a local database, read emails(with specific message).
I am not sure how to craft the code that pushes the results to my Database "EMAIL".
EDIT : I have managed to solve my previous issue of parsing mails and adding it to database. Now I am stuck with type conversion error for Mysql.
Here is my new script:
def parse_email(raw_email):
email_complete = email.message_from_string(raw_email)
email_to = email_complete["To"]
email_from = email_complete["From"]
email_header = email_complete.items()
email_msg = get_first_text_block(email_complete)
con = MySQLdb.connect(host="127.0.0.1", # your host, usually localhost
user="admin", # your username
passwd="pwd", # your password
db="sec_crawl") # name of the data base
con.cursor().execute("INSERT INTO email VALUES (?,?,?,?)",
(buffer(str(email_to)),buffer(str(email_from)),buffer(str(email_header)),buffer(str(email_msg))))
con.commit()
On executing this script, I get the following error :
TypeError: not all arguments converted during string formatting
Here is the part of script that creates the database:
cur.execute("DROP TABLE IF EXISTS EMAIL")
cur.execute("CREATE TABLE email(email_to TEXT,email_from TEXT,email_header TEXT, email_msg TEXT)")
con.close()
I am not sure about the error. I did search some previous questions
Python MySQLdb TypeError: not all arguments converted during string formatting
But the problem is still there.
I am using Python 2.7 on Windows 8.
you have to use %s instead of ? like this
con.cursor().execute("INSERT INTO email VALUES (%s,%s,%s,%s)",
(buffer(str(email_to)),buffer(str(email_from)),buffer(str(email_header)),buffer(str(email_msg))))
'?' are typically used with prepared statements which MySQLdb doesn't support.
This question already has answers here:
Does Python support MySQL prepared statements?
(7 answers)
How to use variables in SQL statement in Python?
(5 answers)
Closed 10 months ago.
I am new to python and i am facing problem while fetching data from mysql db while i am passing parameters in mysql query i think my mysql syntax is incorrect .
Here is the Error displayed on Screen Like this.
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at webmaster#localhost to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log.
Apache/2.4.6 (Ubuntu) Server at localhost Port 80
Here Is My Code For Select query in that I want to fetch data from get parameter of Url.
#!/usr/bin/python2.7
import cgi;
import cgitb; cgitb.enable();
import time, calendar;
print "Content-type: text/html\n\n";
print "<h1>Hello Python</h1>";
#!/usr/bin/python
import MySQLdb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
# Open database connection
db = MySQLdb.connect("localhost","root","123456789","testdrive" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database
sqlstmt = "SELECT * FROM EMPLOYEE WHERE FIRST_NAME = %(first_name)s AND LAST_NAME = %(last_name)s"
try:
# Execute the SQL command
cursor.execute(sqlstmt, {'first_name': first_name, 'last_name': last_name})
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Now print fetched result
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income )
except:
print "Error: unable to fecth data"
# disconnect from server
db.close()
You have an error in this line
sql = "SELECT * FROM EMPLOYEE WHERE FIRST_NAME = '".first_name."' AND LAST_NAME = '".last_name."'"
This isn't PHP, meaning you can't concat strings and variables like this. I assume you wan't to make prepared statements. In that case, you should read following reply.
Relevant part of your code would look like this:
cursor.execute("SELECT * FROM EMPLOYEE WHERE FIRST_NAME = %s AND LAST_NAME = %s", [first_name, last_name])
First off, you should try abstracting all that into a single function you can call outside of CGI, but that's a whole other exercise now. Anyway, if you had done that you can get the stacktrace much easier to see what you did wrong, however, I can see you have a syntax error in the code you helpfully included
sql = "SELECT * FROM EMPLOYEE WHERE FIRST_NAME = '".first_name."' AND LAST_NAME = '".last_name."'"
Python string concatenation uses the + operator, not . like it is in PHP.
Second, this code is not secure. See http://xkcd.com/327/
To fix this, the cursor.execute method provides a second argument to fill out the tokens, this is what you should do
sqlstmt = "SELECT * FROM EMPLOYEE WHERE FIRST_NAME = %(first_name)s AND LAST_NAME = %(last_name)s"
try:
cursor.execute(sqlstmt, {'first_name': first_name, 'last_name': last_name})
...
I think we don't need fetchall() here, which maybe legacy from sqlite code. Just do something like:
for row in cursor:
x = row[0]
y = row[1]
...
Try this code
import mysql.connector
from mysql.connector import Error
try:
mySQLconnection = mysql.connector.connect(host='localhost',
database='python_database',
user='username',
password='passw0rd')
sql_select_Query = "select * from tablename"
cursor = mySQLconnection .cursor()
cursor.execute(sql_select_Query)
records = cursor.fetchall()
for row in records:
print("Sr No = ", row[0], )
print("Name = ", row[1])
print("Age = ", row[2])
print("Gender = ", row[3], "\n")
cursor.close()
except Error as e :
print ("Error connecting MySQL", e)
finally:
#closing database connection.
if(mySQLconnection .is_connected()):
connection.close()
print("MySQL connection is closed Now"
Ref
I am using sqlite to create and connect to a sqlite db foo.db
When I try to do an insert into the DB. I get the following AttributeError
AttributeError: 'sqlite3.Cursor' object attribute 'execute' is read-only
I can't seem to find any information on this error. Does anyone have any idea what this exception means?
I am using python 2.7 with virtualenv.
The following is the code I am trying to execute assume date is a string.
username = 'user'
pwdhash = some_hash_function()
email = 'user#foo.com'
date = '11/07/2011'
g.db = sqlite3.connect('foo.db')
cur = g.db.cursor()
cur.execute = ('insert into user_reg (username,pwdhash,email,initial_date)\
values (?,?,?,?)',
[username,
pwdhash,
email,
date])
g.db.commit()
g.db.close()
Thanks
You're trying to modify an attribute of the cursor. You want to call a method of the cursor.
It should be
cur.execute('insert into user_reg (username,pwdhash,email,initial_date)\
values (?,?,?,?)',
[username,
pwdhash,
email,
date])
Not
cur.execute = ('insert ...
Seems to be a simple syntax error.
You are trying to set a value to the command execute while you have just to call it:
remove the '=' and it should be fine.