how to extract a value from database using python - python

I want to get a value from a database table using python.
I am sending a query and getting value like this:
conn = pymysql.connect(rds_host, user=name, passwd=password,db=db_name, connect_timeout=10)
with conn.cursor() as cur:
cur.execute("SELECT id FROM user_details WHERE email='{}'".format(email)
for row in cur:
id = row[0]
Is there a way to get the value without using for loop.

Couldn't find the doc ?
https://pymysql.readthedocs.io/en/latest/modules/cursors.html#pymysql.cursors.Cursor.fetchone
cursor.fetchone()
Fetch the next row
Also, you definitly DONT want to use string formatting to build your queries (unless you're ok to have your app wide opened to sql injections of couse). You want to use prepared queries instead:
cur.execute("SELECT id FROM user_details WHERE email=?", [email,])

Related

Looping through a list of dictionaries (Python) by using one of the many keys and checking value

I want a Python code that reads a database using pyodbc, and then reads the curser into a list of dictionaries that I want to iterate and find the entry with the key I want.
for example I have this db with this header: ['id', 'user_name', 'user_lname', 'user_username'].
What I want is to print out the entry in the db that has 'user_username'='JOHNN'
This is how the list looks like :
[{'id': 105, 'user_name': 'John', 'user_lname': 'Smith', 'user_username': 'JOHNN'}]
Below is the python code:
from flask import Flask
import pyodbc
app = Flask(__name__)
conn = pyodbc.connect('Driver={SQL Server};'
'Server=DESKTOP-9JKA425;'
'Database=PD;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM Users')
columns = [column[0] for column in cursor.description]
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns, row)))
# for x in results:
print(results)
Please advise
When you want to query a database with specific criteria, it is better to do this by narrowing your SQL query, rather than querying for * and then filtering in Python.
For example:
query = "SELECT * FROM Users WHERE username = 'JOHNN'"
cursor.execute(query)
Using SQL to narrow down your result set will also reduce the amount of data transported over the network and in many cases, SQL databases will do the necessary conditionals faster than Python.
See https://github.com/mkleehammer/pyodbc/wiki/Getting-started#parameters for how to add dynamic parameters safely for SQL queries when using pyodbc, if you simply use parameters directly, you run the risk of introducing SQL injections into your code.
Written safely, the above becomes:
query = "SELECT * FROM Users WHERE username = ?"
cursor.execute(query,'JOHNN')

Inserting Query Results into Singlestore Table with Python and Sqlalchemy

I have parameterized queries with f strings such that the queries will select some data from a series of tables and joins, and I want to insert the resulting set of data into another pre-created table (tables been designed to house these results).
Python executes the code but the query results never show up in my table.
Assuming target_table is already created in singlestore database:
qry_load = 'insert into target_table select * from some_tables'
conn = engine.connect()
trans = conn.begin()
try:
conn.execute(qry_load)
trans.commit()
except:
trans.rollback()
raise
The code executes and acts as if all is ok, but the data never shows up in the target table.
How do I see what singlestore is passing back to better debug what is happening within the database?
Just replace begin() with cursor() function:
conn = engine.connect()
trans = conn.cursor()
If not resolved
1- Verify structure of source and destination tables if they are same or not.
2- remove try ,except and rollback() block so you can know the actual error.
Ex.
qry_load = 'insert into target_table select * from some_tables'
conn = engine.connect()
trans = conn.cursor()
conn.execute(qry_load)
trans.commit()

Python: How to access MySQL DB table using SQLAlchemy

I am making a python GUI that will look up the the status of a helpdesk ticket in a MySQL database. I connected python to an existing MySQL database with SQLAlchemy using the code below.
conn = mysql.connector.connect(user='root',
password='stuff',host='127.0.0.1',
database='mydb')
c = conn.cursor()
I only need access to one of the columns, ticket_id, in a table called tickets. Basically I want to do this:
SELECT ticket_status FROM tickets WHERE ticket_id = 123;
What would be simplest way to do this?
The following code should work at fetching a single value. If you realize later you need to fetch more than one value you can change fetchone() to fetchall()
try:
sql = '''
SELECT ticket_status FROM tickets WHERE ticket_id = 123
'''
c.execute(sql)
result = c.fetchone()
except Exception as e:
raise Exception(e)

Trying to find last insert row ID; returned value is encrypted

I'm using pypyodbc with SQL Server 2016.
I am trying to insert and grab the last id inserted into database following another user's remarks but the returned value seems to be encrypted. Is there a way to decrypt it?
def executeSQL (command):
connection = pypyodbc.connect('Driver={SQL Native Client};'
'Server=blah\blah;'
'Database=Impact;'
'uid=Admin;pwd=F$sfgdfgs99')
cursor=connection.cursor()
cursor.execute(command)
id = cursor.execute("SELECT ##IDENTITY")
connection.commit()
connection.close()
return id
sqlexecute = 'INSERT INTO PERSONS([LastName], [FirstName]) VALUES(\''+lastname.encode('utf-8')+'\',\''+firstname.encode('utf-8')+'\');\n'
lastid = executeSQL(sqlexecute)
print lastid
Output:
<pypyodbc.Cursor instance at 0x000000000B870C88>
It is not encrypted, it is telling you the type of the object that this is an instance of. In this case, it is pypyodbc.Cursor.
To fetch the actual rows, you do id.fetchall() which will return a list of the results. You can then loop over them to read the contents.

Python not committing MySQL transaction

I am inserting a couple thousand records into a table via the python code below:
values = ''
for row in cursor:
values = values + "(" + self.quoted_comma_separate(row) + "),"
values = values[:-1]
insert_statement = "INSERT INTO t1 ({0}) VALUES {1};".format(
self.comma_separate(members), values)
db = Database()
conn = db.get_db()
cursor = conn.cursor()
cursor.execute(insert_statement)
conn.commit()
conn.close()
When I check the database after it runs none of the records show up in the database. If I go into an MySQL editor and manually commit the transaction all of the records appear. Why is my conn.commit() not working?
The insert statements were fine. Turns out I had another database connection open and it was getting confused and committing to the wrong connection or something like that. Sorry for the pointless question :)

Categories