I am running a mysql query from python using mysql.connector library as per code below
cnx = mysql.connector.connect(host=mysql_localhost, user=user, password=password, database=database)
cursor = cnx.cursor()
cursor.execute("select * from settings" )
results = cursor.fetchall()
ID, server, port, user, password, temp_min ,temp_max = results[0]
print(user)
cursor.close()
cnx.close()
the result is as follow
u'admin'
I noticed that values stored in the database as varchar display with u''
how can I get the value without the u'' so the desired output is
admin
u means that this is a unicode string. You should read Unicode HOWTO for better understanding.
You can use str() to get rid of the u:
print str(user)
FYI-the u means it is unicode.
The u in front of your variable means that it is a unicode string. Is that really a problem? If you really need to convert it to a regular string you can use str(user).
Related
ok so I'm trying to code a password manager in python and I'm using cyrptography.fernet to crypt the emails and passwords and then store them into a local SQLite database the problem is that when I try to get for example the emails in the database they are in this format: (b'encypted-email-here'), (b'and-so-on) so I thought since theres the b before the quotes it's in bytes format and I do not need to do anything in order to decrypt them but when I actually try to decrypt them I get an error saying: "TypeError: token must be bytes" here is my code so you can take a look at it
b_email = email.encode('utf-8')
b_pwd = pwd.encode('utf-8')
enc_email = f.encrypt(b_email)
enc_pwd = f.encrypt(b_pwd)
conn = sqlite3.connect('database.db')
execute = conn.cursor()
execute.execute('CREATE TABLE IF NOT EXISTS logins (website, email, password)')
execute.execute('INSERT INTO logins VALUES (:website, :email, :password)', {'website': website, 'email': enc_email, 'password': enc_pwd})
conn.commit()
conn.close()
def view():
con = sqlite3.connect('database.db')
cur = con.cursor()
iterable = cur.execute('SELECT email FROM logins')
for email in iterable:
dec_email = f.decrypt(email)
print(dec_email)```
cur.execute() returns a sequence of rows, each of them is a tuple. In your case, a tuple of just one element, but still you need to extract the email from it. The most elegant way would be unpacking (notice the comma after email):
for email, in cur.execute('SELECT email FROM logins'):
print(f.decrypt(email))
I want to save an API response, on some table of my database, I'm using Postgres along with psycopg2.
This is my code:
import json
import requests
import psycopg2
def my_func():
response = requests.get("https://path/to/api/")
data = response.json()
while data['next'] is not None:
response = requests.get(data['next'])
data = response.json()
for item in data['results']:
try:
connection = psycopg2.connect(user="user",
password="user",
host="127.0.0.1",
port="5432",
database="mydb")
cursor = connection.cursor()
postgres_insert_query = """ INSERT INTO table_items (NAME VALUES (%s)"""
record_to_insert = print(item['name'])
cursor.execute(postgres_insert_query, record_to_insert)
connection.commit()
count = cursor.rowcount
print (count, "success")
except (Exception, psycopg2.Error) as error :
if(connection):
print("error", error)
finally:
if(connection):
cursor.close()
connection.close()
my_func()
I mean, I just wanted to sort of "print" all the resulting data from my request into the db, is there a way to accomplish this?
I'm a bit confused as You can see, I mean, what could be some "print" equivalent to achieve this?
I mean, I just want to save from the API response, the name field, into the database table. Or actually INSERT that, I guess psycopg2 has some sort of function for this circumstance?
Any example You could provide?
EDIT
Sorry, I forgot, if I run this code it will throw this:
PostgreSQL connection is closed
A particular name
Failed to insert record into table_items table syntax error at or near "VALUES"
LINE 1: INSERT INTO table_items (NAME VALUES (%s)
There are a few issues here. I'm not sure what the API is or what it is returning, but I will make some assumptions and suggestions based on those.
There is a syntax error in your query, it is missing a ) it should be:
postgres_insert_query = 'INSERT INTO table_items (NAME) VALUES (%s)'
(I'm also assuming thatNAME` is a real column in your database).
Even with this correction, you will have a problem since:
record_to_insert = print(item['name']) will set record_to_insert to None. The return value of the print function is always None. The line should instead be:
record_to_insert = item['name']
(assuming the key name in the dict item is actually the field you're looking for)
I believe calls to execute must pass replacements as a tuple so the line: cursor.execute(postgres_insert_query, record_to_insert) should be:
cursor.execute(postgres_insert_query, (record_to_insert,))
This question already has an answer here:
MySQL/Python -> Wrong Syntax for Placeholder in Statements?
(1 answer)
Closed 4 years ago.
import mysql.connector
config = {
'user': 'root',
'password': '*******',
'host': '127.0.0.1',
'database': 'mydb',
'raise_on_warnings': True
}
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
find_user = ("SELECT * FROM HM_Login WHERE Username = '%s' ")
data_Pupil = {
'Username': "GJM"
}
cursor.execute(find_user, data_Pupil)
lit = cursor.fetchall()
print(lit)
cursor.close()
cnx.close()
I have a database that works and i am having a problem trying to search the database and pull one row of one column when i was inserting into the database the %S worked just fine but now it only works if i have a value inside the the query. this is using the mysql connector for python.
mysql.connector.errors.ProgrammingError: 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 '' at line 1
I am getting this error which is extremely insightful and not helpful at all if there is anything you can do to help it would mean a lot.
As the error statement says. You have an SQL error. You are trying to input a variable as a positional parameter but you've used a dictionary on a variables 'place'.
Instead you should use %s for variables and tuples with variables and then do the following:
find_user = "SELECT * FROM HM_Login WHERE Username = %s"
data_Pupil = ('GJM',)
cursor.execute(find_user, data_Pupil)
It is also possible to use dictionary - but you shouldn't. Despite that I'm still going to show it here as I had to dig into the explanation to understand why.
find_user = "SELECT * FROM HM_Login WHERE Username = '{Username}'".format(**data_Pupil)
data_Pupil = {
'Username': "GJM"
}
The above opens up for sql-injections, as I was told per the comments - and here is why; Say we have a username that is identical to the following:
username = "'MR SQL Injection');DROP TABLE HM_Login;"
That would result in an SQL Query that drops the table.
SELECT * FROM HM_Login WHERE Username = 'MR SQL Injection');DROP TABLE HM_Login;
To avoid sql-injection as above. Use the first solution
Your placeholder syntax is for positional parameters but you've used a dictionary. Replace that with a tuple:
find_user = ("SELECT * FROM HM_Login WHERE Username = %s")
data_pupil = ('GJM',)
cursor.execute(find_user, data_Pupil)
I have a string with mixed quotes that is " and '. I want to store the string in a Text field in a sqlite3 database using python.
Here is the query I'm using and I have a function that executes these queries.
"""INSERT INTO SNIPPETS (CONTENT, LANGUAGE, TITLE, BACKGROUND)
VALUES("{0}" ,"{1}","{2}", "{3}")
""".format(content, language, title, background)
Something like:
with self.connection as conn:
cursor = conn.cursor()
try:
result = cursor.execute(statement)
if(insert_operation):
return cursor.lastrowid
return result.fetchall()
You don't have to make it too complicated. Python sqlite3 will take care of the quoting for you.
statement = 'INSERT INTO SNIPPETS (CONTENT, LANGUAGE, TITLE, BACKGROUND) VALUES (?, ?, ?, ?)'
cursor.execute(statement, (content, language, title, background))
Simple peewee example:
MySQL DB "Pet" with autoincrement "id" and char-field "name".
Doing
my_pet = Pet.select().where(name == 'Garfield')
With .sql() we get the sql interpretation.
How to get the raw sql query from:
my_pet = Pet.get(name='Garfield')
?
When you write:
my_pet = Pet(name='Garfield')
Nothing at all happens in the database.
You have simply created an object. There is no magic, as peewee is an ActiveRecord ORM, and only saves when you call a method like Model.save() or Model.create().
If you want the SQL for a query like Model.create(), then you should look into using Model.insert() instead:
insert_stmt = Pet.insert(name='Garfield')
sql = insert_stmt.sql()
new_obj_id = insert_stmt.execute()
The downside there is that you aren't returned a model instance, just the primary key.
If you are connecting to a Postgres database, per peewee 3.13 you can print SQL queries by first getting the cursor, then calling mogrify() for your query. Mogrify is provided by the psycopg2 library and hence may not be available when connecting to other databases.
Given your example:
my_pet = Pet.select().where(Pet.name == 'Garfield').limit(1)
cur = database.cursor()
print(cur.mogrify(*my_pet.sql()))
Where database is the Peewee Database object representing the connection to Postgres.
You can use python's "%" operator to build the string
def peewee_sql_to_str(sql):
return (sql[0] % tuple(sql[1]))
insert_stmt = Pet.insert(name='Garfield')
sql = insert_stmt.sql()
print(peewee_sql_to_str(sql))