I am trying to get Information from my database, and print it, but unfortunately, Instead of Printing the Information from the Table, it just Prints 0 or 1.
Why does it do this?
Can someone please help me?
sql = ("SELECT code FROM testing WHERE email = ((%s))")
sql2 = a.execute(sql, (fullemail))
sqlusername = ("SELECT username FROM testing123 WHERE code = ((%s))")
username = a.execute(sqlusername, (sql2))
print("Test3")
print(username)
Thank you.
The execute() method just returns the number of impacted rows.
You must use .fetchall() or equivalent (e.g. .fetchone()...) DBAPI methods to get a resultset.
Also, using parentheses alone around a single value: (fullemail) will not be recognized as a tuple, you need to explicitly add a comma so Python will recognize this as a tuple: (fullemail, )
sql = ("SELECT code FROM testing WHERE email = %s")
a.execute(sql, (fullemail, ))
sql2 = a.fetchall()
print(sql2)
sqlusername = ("SELECT username FROM testing123 WHERE code = %s")
a.execute(sqlusername, (sql2[0][0], ))
username = a.fetchall()
print("Test3")
print(username)
Depending on which library you are using:
MySQLdb (python 2.7)
mysqlclient (MySQLdb for python3)
PyMySQL (pure Python)
You can also use a DictCursor to get your result set rows as dict instead of list. Usage is like:
from pymysql.cursors import DictCursor
import pymysql
db = pymysql.connect(host="", user="", passwd="", cursorclass=DictCursor)
with db.cursor() as cur:
cur.execute("SELECT ...")
results = cur.fetchall()
This will give you a list of dictionaries instead of a list of lists.
Related
I want to take input from user of creating a mysql database I cant use python input to create mysql databasewhat i tryed
Getting this error please help the error
execute() method parameters must be provided as a tuple, dict or a list :
cursor.execute(cdb, (dbname,))
And I think you can execute your query directly like :
%-formatting
cdb = 'CREATE DATABASE %s' % dbname
cursor.execute(cdb)
F-strings
cdb = f'CREATE DATABASE {dbname}'
cursor.execute(cdb)
str.format()
cdb = 'CREATE DATABASE {}'.format(dbname)
cursor.execute(cdb)
Consider using f-strings when dealing with string that contains variables.
cdb = f'CREATE DATABASE {dbname}'
Try this way, this works correctly.
try:import mysql.connector as con
except ImportError:print("⚠ Install correctly mysql.connector")
db = con.connect(host="localhost",user="<username>",passwd="<password>")
cursor = db.cursor()
dbname = input("Enter ddbb name to create: ")
cdb = f"CREATE DATABASE {dbname}"
try:cursor.execute(cdb)
except NameError:print(NameError)
So I'm not so experienced in Python, but I really enjoy making stuff with it.
I decided to start using Python to interact with MySQL in one of my projects.
I would like to write a function that takes the username as input and returns the password as output.
Here is what I've tried to do:
def get_passwd(user_name):
user_passwd = mycursor.execute("SELECT passwd FROM users WHERE name = '%s'", (user_name))
print(user_passwd)
get_passwd("Jacob")
But it's justing printing out "None".
My table looks like this:
Instead of
user_passwd = mycursor.execute("SELECT passwd FROM users WHERE name = '%s'", (user_name))
use something as
mycursor.execute("SELECT passwd FROM users WHERE name = '%s'", (user_name))
row = mycursor.fetchone()
user_passwd = row[0]
It is unclear which package you are using to access your database.
Assuming it is sqlalchemy what you are missing is the fetch command.
So you should add -
def get_passwd(user_name):
user_passwd = mycursor.execute("SELECT passwd FROM users WHERE name = '%s'", (user_name))
user_actual_passwd = user_passwd.fetchone()
print(user_actual_passwd)
get_passwd("Jacob")
See more here
** Update as the question was updated **
I would make sure that the query strings is what you are expecting.
Do -
query = "SELECT passwd FROM users WHERE name = '%s'", (user_name)
print (query)
If the query is what you are expecting, try running it directly on the db and see if you get any result.
I am connecting to mysql database via mysql connector and running a simple query to pull a list of IDs. I need to loop over that list and pass them into some other code. For some reason I am getting a list of tuples. Is this expected behavior? If not, what am I doing wrong?
Here is the snippet of my code:
import mysql.connector
conn = mysql.connector.connect(host='127.0.0.1', database='t', user='r', password='pwd')
cursor = conn.cursor()
query = ( "select id from T where updated < '%s'" % (run_date) )
cursor.execute(query)
for row in cursor:
print (row)
cursor.close()
I am getting the following back (from an INT field in d/b):
(Decimal('991837'),)
(Decimal('991838'),)
(Decimal('991839'),)
(Decimal('991871'),)
(Decimal('991879'),)
(Decimal('991899'),)
(Decimal('992051'),)
(Decimal('992299'),)
(Decimal('992309'),)
if you want to access just the data in the row you need to go into the dictionary
first you must make it true in the cursor
cur = db.cursor( buffered=True , dictionary=True)
then the result will be like this :
{'Decimal' : '991837'}
i'm sure the Decimal is your row name
so when you need to access to the value do this
import mysql.connector
conn = mysql.connector.connect(host='127.0.0.1', database='t', user='r', password='pwd')
cursor = conn.cursor()
query = ( "select id from T where updated < '%s'" % (run_date) )
cursor.execute(query)
for row in cursor:
print (row['Decimal'])
cursor.close()
i hope it works for i was looking for this solution for the past 2 days and no answers
the only way i debugged i opened the debugger and print out all the variables
have fun with Python :)
Yes, this is expected behavior. Using the cursor as an iterable is basically equivalent to looping over it using the fetchone() method. From the documentation for fetchone() (emphasis mine):
This method retrieves the next row of a query result set and returns a
single sequence, or None if no more rows are available. By default,
the returned tuple consists of data returned by the MySQL server,
converted to Python objects. If the cursor is a raw cursor, no such
conversion occurs;
I am trying to use the following additional arguments in the mysql.connector.connect(), however when I run the following code it doesn't seem to have any effect.
import mysql.connector
cnx = mysql.connector.connect(
....
raw='true',
use_unicode='false'
)
cursor = cnx.cursor()
query = ("...")
cursor.execute(query)
result = cursor.fetchall()
print result
[(datetime.date(2015, 4, 5), 1243), ...
where the results has a column of MySQL datetime format values
but even with these arguments the output is still in python datetime.date(YYYY,M,D) format
same issue also when calling col = cursor.column_names, returns unicode instead of strings even though "raw" is set to true.
print cursor.colun_names = (u'string_1', u'string_2')
is there some other configuration needed? i dont want to have to write code to convert these every time its used. thanks!
I think when Python evaluates something like:
if use_unicode:
// do something
Variable use_unicode returns True, because string 'false' evaluated to True. Try to use Boolean values.
import mysql.connector
cnx = mysql.connector.connect(
....
raw=True,
use_unicode=False
)
cursor = cnx.cursor()
query = ("...")
cursor.execute(query)
result = cursor.fetchall()
print result
raw=True means:
A MySQLCursorRaw cursor skips the conversion from MySQL data types to
Python types when fetching rows. A raw cursor is usually used to get
better performance or when you want to do the conversion yourself.
So you get ByteArray as expected. I don't know what exactly you are trying to do, but when I work with MySQL in Python, I prefer to work with dictionary data structure.
cursor = cnx.cursor(dictionary=True)
And then you will get result as dictionary. If you want to view it as string, just do print str(dict)
import mysql.connector
cnx = mysql.connector.connect(user=self.username, password=self.password, host=self.host, database=self.database);
cursor = cnx.cursor(dictionary=True)
query = ("...")
cursor.execute(query)
result = cursor.fetchall()
print str(result)
I have a problem with deleting a record from my SQLite3 database:
conn = sqlite3.connect('databaza.db')
c = conn.cursor()
data3 = str(input('Please enter name: '))
mydata = c.execute('DELETE FROM Zoznam WHERE Name=?', (data3,))
conn.commit()
c.close
Everything is OK, no errors, but the delete function doesn't work!
Does anyone have an idea?
The correct syntax for a parameterized query is:
mydata = c.execute("DELETE FROM Zoznam WHERE Name=?", (data3,))
Make sure the parameter uses the comma, to make it a python tuple.
This will help prevent SQL Injection which is possible when passing in a formatted string. More on SQL Injection here
Related post here.
I'm a little late to the party but if you Google search "python sqlite delete row" This is the first thing that comes up and I was having the same issue where things were not getting DELETE'd from my sqlite DB.
I'm using Python 2.7 on Debian Jessie.
Previously, when I wrote Python code for adding and retrieving information in the sqlite database, I had written the commands with correct capitalization where needed and it worked.
curs.execute("SELECT example_column1 FROM example_table WHERE example_column2=(?)", (Variable,))
However...
curs.execute("DELETE FROM example_table WHERE example_column1=(?)", (Variable,)):
This for some reason does not work with the DELETE command. I had to send that command in all lower-case before sqlite would respect the command being sent.
conn=sqlite3.connect('example.db')
curs=conn.cursor()
curs.execute("delete from example_table where example_column=(?)", (Variable,))
conn.commit()
conn.close()
I have no idea why.
I tried all the previously mentioned methods but having the command sent in lowercase was the only way I could get it to work.
Hope this helps any struggling neophytes in their journey into Python and sqlite.
Try with:
mydata = c.execute('DELETE FROM Zoznam WHERE Name = (?)', (data3))
Without the ',' and the '?' between '()'
I'm using Python 3.9 on windows.
c.execute("DELETE FROM Zoznam WHERE Name={0}".format(data3))
conn.commit()
I advise you to first make a string for the query , and then execute it. ex:
query = "delete from zoznam where name = '%s' " % data3
c.execute(query)
conn.commit()
Check the file permissions.
An aside, I prefer the tokenized method:
mydata = c.execute("DELETE FROM Zoznam WHERE Name='%s'" % data3)
Thank you to everybody who tried to help. The right code is:
conn = sqlite3.connect('databaza.db')
c = conn.cursor()
conn.text_factory = str
data3 = str(input('Please enter name: '))
query = "DELETE FROM Zoznam WHERE Name = '%s';" % data3.strip()
print(query)
mydata = c.execute(query)