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.
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)
I'm trying to make a program in Python that requests an input and if the table in the DB exists, writes to it, and if it doesn't, creates it.
Here is the existing code:
connection = sqlite3.connect('AnimeScheduleSub.db')
cursor = connection.cursor()
anime_id = input('enter server id')
discord_user_id = int(input('Enter token'))
try:
cursor.execute("SELECT * FROM {}".format(anime_id))
results = cursor.fetchall()
print(results)
except:
command1 = f"""CREATE TABLE IF NOT EXISTS
{anime_id}(discord_user_id INTEGER)"""
cursor.execute(command1)
Basically, what it's doing (or what I'm trying to achieve) is the try loop is meant to check if the anime_id table exists. The except loop is meant to create the table if the try loop failed.
But it doesn't work, and I have no idea why. Any help would be much appreciated.
command1 = f"""CREATE TABLE IF NOT EXISTS
A{anime_id}(discord_user_id INTEGER)"""
Creating table name with just numbers are not supported by sql.
You should start with a letter and then use numbers.
You should "ask" the DB if the table is there or not.
Something like the below.
anime_id = input('enter server id')
SELECT name FROM sqlite_master WHERE type='table' AND name='{anime_id}';
I'm trying to write code where after giving name and email input in the command prompt it should update the data in the Postgres database. English is not my first language, but I'll try my best to describe my situation.
So basically when typing in the cmd:
python myProgram.py jacob8 jacob8#company.com
It should update the jacob8 in the username column and jacob8#company.com in the email column.
So my code is like this:
import sys
import psycopg2
conn = psycopg2.connect("user=nana password=nana dbname=nana host=localhost")
cur = conn.cursor()
userName = str(sys.argv[1])
eMail = str(sys.argv[2])
cur.execute('UPDATE "table" SET "user_name" = userName WHERE "address"=%s', (mac,))
cur.execute('UPDATE "table" SET "user_email" = eMail WHERE "address"=%s', (mac,))
conn.commit()
...but for some reason userName that Im using where I'm trying to SET, doesn't recognize the userName that I assigned as sys.argv[1] and the same goes about eMail. When I'm adding them inside single quotation marks, it's recognized, but it messes up (makes the rest of the line green) the rest of the line starting with WHERE.
I also tried to put sys.argv[1] and sys.argv[2] straight into SET line (like UPDATE "table" SET "user_name" = sys.argv[1] WHERE) but it gives me the same kind of problem - it wont recognize the import sys anymore.
What am I missing here? It's clearly something to do with how to add quotation marks but I can't find the correct way..
You need placeholders for all locations where you want to substitute parameterized data -- so not just mac, but also userName and eMail.
Personally, for readability's sake, I'd write this as just one query doing both updates, as follows:
query = '
UPDATE table
SET user_name = %(name)s, user_email = %(email)s
WHERE address = %(mac)s
'
cur.execute(query, {'name': userName, 'email': eMail, 'mac': mac})
That said, the shortest possible change is just:
cur.execute('UPDATE "table" SET "user_name" = %s WHERE "address"=%s', (userName, mac,))
cur.execute('UPDATE "table" SET "user_email" = %s WHERE "address"=%s', (eMail, mac,))
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.
I am aware this may be a duplicate post. However I have looked at the other posts and cant figure it out in my case.
from configdata import configdata
from dbfiles.dbconnect import connection
c,conn = connection()
table = configdata()[4]
userid = 'jdeepee'
value = c.execute("SELECT * FROM %s WHERE userid = (%s)" % (table), userid)
print(value)
I think the code is self explanatory. But essentially what I am trying to do is query a MySQL database based on a variable for the integer and userid. I believe my syntax is wrong not sure how to fix it however. Help would be great.
Try this:
value = c.execute("SELECT * FROM {} WHERE userid = %s".format(table), (userid,))
Basically, you need to interpolate the table name into the query first, then pass any query parameters to .execute() in a tuple.