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,))
Related
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)
My variable values are derived from the edited grid cell. The function works but the edited field name is named "Read". I fixed it by changing the column name, but I am curious why that is an error and if there are any other field name titles I should avoid.
Message=(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 'Read = 'ALL' where User_ID = 'j_adams58'' at line 1")
Table fields
| User_ID | Password | Read | Edit |
def onCellChanged(self,event):
#Establish connection
self.connect_mysql()
#Update database
key_id = str(self.GetCellValue(event.GetRow(),1))
target_col = str(self.GetColLabelValue(event.GetCol()))
key_col = str(self.GetColLabelValue(1))
nVal = self.GetCellValue(event.GetRow(),event.GetCol())
sql_update = f"""Update {tbl} set {target_col} = %s where {key_col} = %s"""
row_data = ''
self.cursor.execute(sql_update, (nVal, key_id,))
#Close connection
self.close_connection()
Read is a reserved keyword in MySQL, so you shouldn't use it as a column name, but if you really need to, you should be able to access it by putting single backticks around it, like `Read`, but again, it's really bad style and you shouldn't do it. You should also avoid using other keywords, but it's usually best to try the queries you'll run in SQL first so you can check if you can.
See: https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-8-0-detailed-R
Hello everyone I have this sql file :
Student.sql
Select * from student where age > 18;
Delet student_ name , studen_id if age > 18 ;
Commit;
Using cx_oracle pip
Any help
Instead of executing a file, you could execute have the query defined in your code.
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('Host Name', 'Port Number', service_name='Service Name') #if needed, place an 'r' before any parameter in order to address any special character such as '\'.
conn = cx_Oracle.connect(user=r'User Name', password='Personal Password', dsn=dsn_tns) #if needed, place an 'r' before any parameter in order to address any special character such as '\'. For example, if your user name contains '\', you'll need to place 'r' before the user name: user=r'User Name'
query = """
Select * from student where age > 18;
DeletE student_ name , studen_id if age > 18
"""
c = conn.cursor()
c.execute(query) # use triple quotes if you want to spread your query across multiple lines
print('Result', c)
#conn.close()
As other replies noted you can only execute a statement at a time with cx_Oracle. However you can write a wrapper to read your SQL files and execute each statement. This is a lot easier if you restrict the SQL syntax (particularly regarding line terminators). For an example, see https://github.com/oracle/python-cx_Oracle/blob/master/samples/SampleEnv.py#L116
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 trying to check for a string that is being passed from a form in an html page. So the form picks up the user name and then checks the database if it already has been made. If it hasn't, it goes ahead and creates it. My errors are in the part of the logic that looks up that user name.
Note, I have commented out some areas where various errors have popped up:
import mysql.connector
import web
from mysql.connector import Error
import cgi, cgitb
cgitb.enable()
conn = mysql.connector.connect(host='localhost', database='database', user='root', password='root')
cursor = conn.cursor()
form = cgi.FieldStorage()
username = form.getvalue('username')
password = form.getvalue('password')
# check_existence = """
# SELECT username FROM members WHERE username = '%s'
# """
check_existence = """
SELECT username FROM members WHERE username = %s
"""
# cursor.execute(check_existence, username)
# "Wrong number of arguments during string formatting")
cursor.execute(check_existence, (username))
# ^pushes down to con.commit
# cursor.execute(check_existence, (username,))
# ^wrpmg number of arguments during string formatting
# with comma, the error is in commit, with comma, its in execute
conn.commit()
matches = cursor.rowcount()
Now the error is pointing to conn.commit. Though this is depending on the syntax, sometimes it points to the line above it.
Error:
=> 203 conn.commit()
<class 'mysql.connector.errors.InternalError'>: Unread result found.
args = (-1, 'Unread result found.', None)
errno = -1
message = ''
msg = 'Unread result found.'
In my limited experience, commit() is only used to save (commit) updates to the database. It looks like you're executing a select query, but doing nothing with the results, and the error is related to that. Try moving the commit to the end, or doing away with it. Try using/doing something with the results stored in the cursor. I believe the latter is the solution.
The .commit method was off to a start but it wasn't the only problem with the code. I had two problems though one of them is not posted in the original post, I will explain both.
A) cursor.rowcount returns -1. Not sure why but it does. My understanding of it was that it will return the number of rows. But you can use cursor.fetchall() instead. This will return matches in an array....but if the array is empty, it'll return an empty array.
So I used this logic:
if not(cursor.fetchall()):
the set/array is empty>> Create user
else:
something was found >>dont create user
B) This was in the rest of my code. I was checking if the connection was connected:
if conn.is_connected():
The problem with doing this is that if you do this after a .execute, it will return false. So I put it higher up in the logic, to check right when it attempts to connect to the database.