i cant use python input to create mysql database - python

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)

Related

Error executing cursor.execute when quotes are required

fairly new to SQL in general. I'm currently trying to bolster my general understanding of how to pass commands via cursor.execute(). I'm currently trying to grab a column from a table and rename it to something different.
import mysql.connector
user = 'root'
pw = 'test!*'
host = 'localhost'
db = 'test1'
conn = mysql.connector.connect(user=user, password=pw, host=host, database=db)
cursor = conn.cursor(prepared=True)
new_name = 'Company Name'
query = f'SELECT company_name AS {new_name} from company_directory'
cursor.execute(query)
fetch = cursor.fetchall()
I've also tried it like this:
query = 'SELECT company_name AS %s from company_directory'
cursor.execute(query, ('Company Name'),)
fetch = cursor.fetchall()
but that returns the following error:
stmt = self._cmysql.stmt_prepare(statement)
_mysql_connector.MySQLInterfaceError: 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 '? from company_directory' at line 1
I'm using python and mySQL. I keep reading about database injection and not using string concatenation but every time I try to use %s I get an error similar to the one below where. I've tried switching to ? syntax but i get the same error.
If someone could ELI5 what the difference is and what exactly database injection is and if what I'm doing in the first attempt qualifies as string concatenation that I should be trying to avoid.
Thank you so much!
If a column name or alias contains spaces, you need to put it in backticks.
query = f'SELECT company_name AS `{new_name}` from company_directory'
You can't use a placeholder for identifiers like table and column names or aliases, only where expressions are allowed.
You can't make a query parameter in place of a column alias. The rules for column aliases are the same as column identifiers, and they must be fixed in the query before you pass the query string.
So you could do this:
query = f"SELECT company_name AS `{'Company Name'}` from company_directory'
cursor.execute(query)

Creating a table based on input, if input doesnt exist in db file creates a table, if exists, writes ID to it

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}';

Compile query from raw string (without using .text(...)) using Sqlalchemy connection and Postgres

I am using Sqlalchemy 1.3 to connect to a PostgreSQL 9.6 database (through Psycopg).
I have a very, very raw Sql string formatted using Psycopg2 syntax which I can not modify because of some legacy issues:
statement_str = SELECT * FROM users WHERE user_id=%(user_id)s
Notice the %(user_id)s
I can happily execute that using a sqlalchemy connection just by doing:
connection = sqlalch_engine.connect()
rows = conn.execute(statement_str, user_id=self.user_id)
And it works fine. I get my user and all is nice and good.
Now, for debugging purposes I'd like to get the actual query with the %(user_id)s argument expanded to the actual value. For instance: If user_id = "foo", then get SELECT * FROM users WHERE user_id = 'foo'
I've seen tons of examples using sqlalchemy.text(...) to produce a statement and then get a compiled version. I have that thanks to other answers like this one or this one been able to produce a decent str when I have an SqlAlchemy query.
However, in this particular case, since I'm using a more cursor-specific syntax %(user_id) I can't do that. If I try:
text(statement_str).bindparams(user_id="foo")
I get:
This text() construct doesn't define a bound parameter named 'user_id'
So I guess what I'm looking for would be something like
conn.compile(statement_str, user_id=self.user_id)
But I haven't been able to get that.
Not sure if this what you want but here goes.
Assuming statement_str is actually a string:
import sqlalchemy as sa
statement_str = "SELECT * FROM users WHERE user_id=%(user_id)s"
params = {'user_id': 'foo'}
query_text = sa.text(statement_str % params)
# str(query_text) should print "select * from users where user_id=foo"
Ok I think I got it.
The combination of SqlAlchemy's raw_connection + Psycopg's mogrify seems to be the answer.
conn = sqlalch_engine.raw_connection()
try:
cursor = conn.cursor()
s_str = cursor.mogrify(statement_str, {'user_id': self.user_id})
s_str = s_str.decode("utf-8") # mogrify returns bytes
# Some cleanup for niceness:
s_str = s_str.replace('\n', ' ')
s_str = re.sub(r'\s{2,}', ' ', s_str)
finally:
conn.close()
I hope someone else finds this helpful

Python MySQL Statement output: 0 or 1

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.

Mysqldb Update error with set %s

I have created a database with MySQLdb.
In database I have a table with name student with columns:
id(is int),
id_user(is int),
f_name(is str),
l_name(is str)
I want to update a row.
My code is below:
db=mdb.connect(host="localhost", use_unicode="True", charset="utf8",
user="", passwd="", db="test")
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql="""SELECT id_user FROM student"""
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()
rows = cursor.fetchall()
the=int(7)
se=str('ok')
for row in rows:
r=int(row[0])
if r==the:
sql2 = """UPDATE student
SET f_name=%s
WHERE id_user = %s"""% (se,the)
# Execute the SQL command
cursor.execute(sql2)
# Commit your changes in the database
db.commit()
db.rollback()
# disconnect from server
db.close()
When I run it I take the error there is column with name ok why?
Can anyone help me find what I am doing wrong please?
str doesn't wrap its argument in quotation marks, so your statement is this:
UPDATE student SET f_name=ok WHERE id_user = 7
when it needs to be this:
UPDATE student SET f_name='ok' WHERE id_user = 7
So, either change this line:
SET f_name=%s
to this:
SET f_name='%s'
or else change this line:
se=str('ok')
to this:
se="'" + str('ok') + "'"
Though I recommend reading about SQL injection, which will become a concern as soon as you start using user-supplied data instead of hard-coded values.
You should run the query like this:
sql2 = """UPDATE student
SET f_name = %s
WHERE id_user = %s"""
cursor.execute(sql2, (se, the))
Don't use string interpolation, let the database driver handle passing the parameters for you. Otherwise you have to deal with syntax errors like this, or worse, SQL injection.
More details here.
You should always enclose your data with quotes.
Instead of %s solely use '%s' the only types you dont need it are numeric ones, but even there i would enclose %d with '%d' cos it is more save.
And you should use at least db.escape_string(your_data) before inserting or updating same values into your database.
Or have a look at the pdo-using style of mysqldb:
http://mysql-python.sourceforge.net/MySQLdb.html#some-examples
c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
WHERE price < %s""", (max_price,))

Categories

Resources