I want to connect to MySql database using Python through PythonAnywhere, without creating a Flask/Django application.
I have seemingly managed to connect through MySQLdb, using the code below, but I do not receive a response when I run the code. Any solutions?
import MySQLdb
db = MySQLdb.connect(
host = "myuser.mysql.pythonanywhere-services.com",
user = "myuser",
passwd = XXX,
db = "myuser$db_name"
)
cursor = db.cursor()
cursor.execute("SELECT * FROM table_name")
for x in cursor:
print(x)
cursor.close()
db.close()
You retrieve all rows in the table, without error.
cursor.execute("SELECT * FROM table_name")
for x in cursor:
print(x)
Yet you see no output. This is normal for a table that contains zero rows.
Consider doing one or more INSERTs, and a COMMIT,
prior to the query.
Related
I am currently developing a program in python that interacts with multiple database. I am using pyodbc to connect, and execute queries. One of the database is an azure database. I noticed sometimes the sent data is not updated in the database although the program run successfully and no error was thrown. Is there any practices that i should follow to make sure this doesn't happen or is this related to my code or db connection issue? I am a beginner. Would appreciate everyone's help thank you!
Also is the .commit() line should be run after every sql run?
The program should be updating a row of data in the database based on a condition, this particular query sometimes doesn't take effect, but no error was thrown. I also executed multiple queries after that, no issue was found for the next queries. It is successfully executed.
the query is a simple query which is
UPDATE DraftVReg SET VRStatus = 'Potential Duplicate Found' WHERE RowID = ?
I tried to reproduce your scenario on my end and was able to update the SQL row in the Azure SQL DB with Pyodbc module.
Yes, Its very necessary to use
conn.commit
to commit your changes inside a database after you perform operations such as Update or Insert inside Azure SQL DB programmatically.
1) Fetch Data with Select statement.
I was able to fetch the Table’s data successfully with Select * from ‘Tablename’ query inside pyodbc code before I try UPDATE statement.
import pyodbc
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};''SERVER=tcp:sqlservernamesql.database.windows.net,1433;''DATABASE=databasename; UID=siliconuser;PWD=Password;')
#conn.commit()
cursor = conn.cursor()
cursor.execute('Select * FROM StudentReviews')
#conn.commit()
for i in cursor:
print(i)
cursor.close()
conn.close()
Result:-
2) UPDATE the rows require conn.commit()
Code :-
import pyodbc
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};''SERVER=tcp:siliconserversql.database.windows.net,1433;''DATABASE=silicondb; UID=userid; PWD=Password;')
cursor = conn.cursor()
#cursor.execute('Select * FROM StudentReviews')
cursor.execute("UPDATE StudentReviews SET ReviewTime = ('7') WHERE ReviewText = ('SQL DB')")
conn.commit()
cursor.close()
conn.close()
Result:-
Update statement Executed successfully and the Table Row was updated in Azure SQL, Refer Below :-
3) With autocommit=true
Thank you #Gord thompson for the comment and suggestion!
Code :-
import pyodbc
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};''SERVER=tcp:siliconserversql.database.windows.net,1433;''DATABASE=silicondb; UID=username; PWD=Password;', autocommit=True)
#conn.commit()
cursor = conn.cursor()
cursor.execute("UPDATE StudentReviews SET ReviewTime = ('8') WHERE ReviewText = ('SQL DB')")
cursor.close()
conn.close()
Results :- With autocommit=true, You do not need to add conn.commit everytime you update the SQL DB.
I am creating a program that uses VS Code and MySQL Workbench 8.0 together. I am stuck and do not know how to connect the two software together
I also have to be able to upload records into a table that is stored in MySQL Workbench from the Python program that uses variables.
Please tell me if their are any details missing.
Thank you.
For connection:
I have researched on Google and have been unable to find an answer. I have found that I have to install certain packages and use the connect method. However, I do not know the parameters of the connect function.
For uploading data into table:
I have found that I have to create a cursor to somehow upload the data to the table, but am unsusre of the full details.
There are many packages in python that can connect to the mysql database, here we take pymysql as an example.
Install pymysql
pip install PyMySQL
I have already installed, so the prompt package already exists.
Sample code, query and insert data
import pymysql
con = pymysql.Connect(
host='localhost',
port=3306,
user='root',
password='123456',
db='test',
charset='utf8'
)
cur = con.cursor()
sql1 = 'select * from student'
cur.execute(sql1)
data = cur.fetchall()
cur.close()
con.close()
for i in data:
print(str(i))
Add an insert data statement, and re-query after inserting data.
import pymysql
con = pymysql.Connect(
host='localhost',
port=3306,
user='root',
password='123456',
db='test',
charset='utf8'
)
cur = con.cursor()
sql2 = 'insert into student values("002","jerry","W");'
cur.execute(sql2)
sql1 = 'select * from student'
cur.execute(sql1)
data = cur.fetchall()
con.commit()
cur.close()
con.close()
for i in data:
print(str(i))
I'm trying to query a MySQL DB to retrieve a list of variables. Am I doing something wrong here?
# import required modules
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='123.12.123.12',
port=3306,
user='db_user',
password='db_pass',
database='db_mcmods',
cursorclass=pymysql.cursors.DictCursor)
with connection:
with connection.cursor() as cursor:
# Read a single record
#Setting variables as n,v,l to use later.
sql = "SELECT `master_mods`.`Name` AS n, `master_mods`.`Version` AS `n`, `master_mods`.`Link` AS `n` FROM `master_mods`"
cursor.execute(sql)
numrows = cursor.rowcount()
for x in xrange(0,numrows):
row = cursor.fetchone()
print(row[x])
This is the error that my DB throws:
(HY000/1045)
Things I have tried:
Checked DB User Permissions
Checked Connection Values
Fixed Mismatched encoding between DB & Table
Ran query through PHPMyAdmin to check validity
Here is my
Table Structure
Ok, so I figured it out and forgot to post the answer. It ended up being a weird error with cpanel, I had to reset my database user pw twice before it ended up working.
TL;DR Password issue. Appreciate the help everyone.
After reading many thread here i didn't resolved my problem, my code works with a free database created in this website (freemysqlhosting.net), but it doesn't work with my own database on a hosting webiste. My code ('******' for privacy):
#!/usr/bin/python3
import pymysql
db = pymysql.connect("sql.******.it", "******", "******", "******")
cursor = db.cursor()
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
print(results)
db.close()
Here the error:
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'sql.******.it' ([Errno 101] Network is unreachable)")
From command line I would use ping, and then nc. I mean, just cut things to minimum, an check if that works. So first validate if host is valid, and your host can resolve it to IP. Next check if you can connect to that host, on provided port. Here is sample in python.
If I have to bet - I would say, you are missing port... Just double check all names, docs provided by the hosting.
Have you tried using mysql.connector? That's what I use maybe it will work
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
I need to insert JSON data from tornado to postgres, so here's test like this:
from psycopg2 import connect
conn = connect("user='pguser' host='localhost' dbname='pgdb' password='pgpass'")
cursor = conn.cursor()
data = '[{"id":"sdf","name":"wqe","author":"vb"}]'
for row in eval(data):
print row
cursor.execute("""INSERT INTO books(id,name,author) VALUES('%s','%s','%s')""" % \
(row['id'], row['name'], row['author'])
)
>>> cursor.execute("SELECT * FROM books")
>>> cursor.fetchall()
[('sdf', 'wqe', 'vb')]
>>>
$> psql -d pgdb -U pguser -W
Password for user pguser:
psql (9.1.6)
Type "help" for help.
pgdb=> select * from books;
id | name | author
----+------+--------
(0 rows)
As you can see after doing select in python shell, there's some data, but in psql there's
0 rows! What may I be doing wrong?
Python 2.7.2+
You didn't commit the transaction.
Psycopg2 opens a transaction automatically, and you must tell it to commit in order to make the data visible to other sessions.
See the psycopg2 FAQ and the connection.commit() method.
Just had the same perplexing issue. To put options together:
as #Craig Ringer writes after cursor.execute you can run connection.commit
cursor.execute('INSERT INTO table VALUES(DEFAULT, %s)', email)
...
connection.commit()
OR
after connect set autocommit
connection = connect("user='pguser' host='localhost' dbname='pgdb' password='pgpass'")
connection.autocommit = True
OR
use set_session to set autocommit
connection = connect("user='pguser' host='localhost' dbname='pgdb' password='pgpass'")
connection.set_session(autocommit=True)
All worked for me.