SQL SELECT statement is not working? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
def showallres():
sql = '''SELECT ResidentID,FirstName,SurName,Age,MDisability,History,Impairment,Money,Contact
FROM tblResidentM'''
results = run_sql2(sql)
print(results)
return results
for some reason it just prints 'None'? But it worked before. The table and all the fields are named correctly so I am unsure of what it is.
Here is the code for 'run_sql2'
def run_sql2(sql):
db = db_connect()
c = db.cursor()
c.execute(sql)
results=c.fetchall()
db.commit()
c.close()
db.close()
I am connecting to an online mysql database.
db_connect is as follows
def db_connect():
try:
db = mysql.connector.connect(user = 'user', password = 'pass', host = 'host', database = 'db', port = 'port')
print('connected')
return db
except mysql.connector.Error as error:
print(error)

Your function run_sql2() does not return anything,
in Python a function returns None by default, that's why results is None
def run_sql2(sql):
db = db_connect()
c = db.cursor()
c.execute(sql)
results = c.fetchall()
db.commit()
c.close()
db.close()
return results # <---- you must return the results

Related

Python- Mysql - Password with # [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 days ago.
Improve this question
How do I connect to mysql database from python when my password contains a "#"
Getting this error:
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'user_name'#'1.2.3.4' (using password: YES)
import mysql.connector
from urllib import parse
host = 'host.rds.xyz.com'
p = parse.quote("pass#2023")
# Connect to the database
mydb = mysql.connector.connect(
host= host,
user="user_name",
password= p
)
You can escape the special character with \ like below:
p = "pass\#2023"
or
p = "'pass#2023'"
The latter one contains the quotations ('pass#2023'). This can come in handy if you need to call a function with a string parameter with quotes.
sorry..this is very embarrassing...my account was locked
I was able to connect without any parsing/escape..
The error deceived me as I had to escape # while connecting to Oracle..I thought mysql worked the same..but it seems mysql.connector takes care of special chars...
import mysql.connector
host = 'host.rds.xyz.com'
p = "pass#2023"
# Connect to the database
mydb = mysql.connector.connect(
host= host,
user="user_name",
password= p
)

sqlite3 add row to table doesnt add no errors

I have an SQLite3 database that I want to add to with python, this is the code i have to add a row
def create_connection(db_file):
""" create a database connection to a SQLite database """
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
def add_password(conn, data):
"""
Create an entry into the password database
"""
try:
sql = 'INSERT INTO passwords(added,username,password,website,email) VALUES(?,?,?,?,?)'
cur = conn.cursor()
cur.execute(sql, data)
print('done')
return cur.lastrowid
except Error as e:
print(e)
connection = create_connection('passwords.db')
data = (datetime.now(), 'SomeUsername', 'password123', 'stackoverflow.com', 'some#email.com')
add_password(connection, data)
When I run it prints done and ends, there are no errors. However, when I open the database to view the table, it has no entries.
If I open the database and run the same SQL code
INSERT INTO passwords(added,username,password,website,email)
VALUES('13-5-2020', 'SomeUsername', 'password123', 'stackoverflow.com', 'some#email.com')
it adds to the table. So it must be a problem with my python code. How do I get it to add?
Just make conn.commit() after executing query. It should work

Invalid Syntax error on try clause in Python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
First I apologize if this is formatted poorly, I've never asked a question here before.
I'm running python 2.7.15 in a virtualenv on win10-64. I'm trying to upload some test strings to a MySQL database but I'm getting the dumbest error and I don't know how to get around it. The MySQL Python/Connector should be installed correctly. Same with the GCP SDK.
import mysql.connector
from mysql.connector import errorcode
# Config info will be moved into config file(s) after testing
# Google Proxy Connection (Proxy must be running in shell)
# C:\Users\USER\Google Drive\Summer Education\GCP
# $ cloud_sql_proxy.exe -instances="pdf2txt2sql-test"=tcp:3307
config1 = {
'user': 'USER',
'password': 'PASSWORD',
'host': 'IP',
'port': '3307',
'database': 'pdftxttest',
'raise_on_warnings': True,
}
# Direct Connection to Google Cloud SQL
config2 = {
'user': 'USER',
'password': 'PASSWORD',
'host': 'IP',
'database': 'pdftxttest',
'raise_on_warnings': True,
}
try:
cnx = mysql.connector.connect(**config1)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
print("Connection not made")
cursor = cnx.cursor()
# Test information
id = str(1)
testtitle = str("Look a fake title")
teststring = str('thislistis representingaveryshort pdfwithfuckedup spaces')
add_pdf = ("INSERT INTO pdftexttest (id, title, text) VALUES (%s, %s, %s)", (id, testtitle, teststring)
try:
cursor.execute(add_pdf)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_BAD_TABLE_ERROR:
print("no pdf for you")
else:
print(err)
print("here")
cnx.commit()
cursor.close()
cnx.close()
After running this code I get
(env) C:\Users\USER\Google Drive\Summer Education\ProjPdf2Txt>python TXT2SQL.py
File "TXT2SQL.py", line 47
try:
^
SyntaxError: invalid syntax
I have some previous experience in java but I'm still a novice programmer.
If I remove the Try...Except clause and go straight to cursor.execute() the console tells me
(env) C:\Users\USER\Google Drive\Summer Education\ProjPdf2Txt>python TXT2SQL.py
File "TXT2SQL.py", line 46
cursor.execute(add_pdf)
^
SyntaxError: invalid syntax
You were missing a parentesis there.
add_pdf = ("INSERT INTO pdftexttest (id, title, text) VALUES (%s, %s, %s)", (id, testtitle, teststring))
In previous line
add_pdf = ("INSERT INTO pdftexttest (id, title, text) VALUES (%s, %s, %s)", (id, testtitle, teststring)
You open ( but didn't close it.

How do I connect to a SQL server database with python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Im trying to conennect to an sql database that its already created an that its located on a server. How can I connect to this database using python. Ive tried using java but I cant seem to get working either.
Well depending on what sql database you are using you can pip install pymssql for microsoft sql (mssql), psycopg2 for postgres (psql) or mysqldb for mysql databases
Here are a few examples of using it
Microsoft sql
import pymssql
conn = pymssql.connect(server=server, user=user, password=password, database=db)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(MemberID) as count FROM Members WHERE id = 1")
row = cursor.fetchone()
conn.close()
print(row)
Postgres
import psycopg2
conn = psycopg2.connect(database=db, user=user, password=password, host=host, port="5432")
cursor = conn.cursor()
cursor.execute('SELECT COUNT(MemberID) as count FROM Members WHERE id = 1')
row = cursor.fetchone()
conn.close()
print(row)
mysql
import MySQLdb
conn = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
cursor = conn.cursor()
cursor.execute('SELECT COUNT(MemberID) as count FROM Members WHERE id = 1')
row = cursor.fetchone()
conn.close()
print(row)

Sqlite insert query not working with python?

I have been trying to insert data into the database using the following code in python:
import sqlite3 as db
conn = db.connect('insertlinks.db')
cursor = conn.cursor()
db.autocommit(True)
a="asd"
b="adasd"
cursor.execute("Insert into links (link,id) values (?,?)",(a,b))
conn.close()
The code runs without any errors. But no updation to the database takes place. I tried adding the conn.commit() but it gives an error saying module not found. Please help?
You do have to commit after inserting:
cursor.execute("Insert into links (link,id) values (?,?)",(a,b))
conn.commit()
or use the connection as a context manager:
with conn:
cursor.execute("Insert into links (link,id) values (?,?)", (a, b))
or set autocommit correctly by setting the isolation_level keyword parameter to the connect() method to None:
conn = db.connect('insertlinks.db', isolation_level=None)
See Controlling Transactions.
It can be a bit late but set the autocommit = true save my time! especially if you have a script to run some bulk action as update/insert/delete...
Reference: https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.isolation_level
it is the way I usually have in my scripts:
def get_connection():
conn = sqlite3.connect('../db.sqlite3', isolation_level=None)
cursor = conn.cursor()
return conn, cursor
def get_jobs():
conn, cursor = get_connection()
if conn is None:
raise DatabaseError("Could not get connection")
I hope it helps you!

Categories

Resources