python to MySQL within pythonAnywhere - python

I'm trying to enter data from python 3.4 into a MySQL database, with both of these entities being within pythonAnywhere. In other words, I'm writing a python 3.4 program in pythonAnywhere and need to connect to a MySQL db also within pythonAnywhere. I've checked other answers here and haven't quite figured it out. I've tried the ( -u -h -p) syntax mentioned by a few posts, but I'm not sure if that is just for gaining access from outside of pythonAnywhere.
Any help would be appreciated.
++++++++++++++++++++
Actually I figured it out (with kudos to Tony Darnell at the Scripting MySQL website, from whom I plagiarized most of this:
import MySQLdb
db=MySQLdb.connect(
host='Your_User_Name.mysql.pythonanywhere-services.com',
user='Your_User_Name',
passwd='Your_pythonAnywhere_password',
db='Your_User_Name$Your_Data_Base')
everything above starting with 'Your' refers to you personal account info with pythonanywhere
everything else gets listed exactly as shown. Watch that $ that follows your user name as part of the database name (db = etc.)
cursor = db.cursor ()
execute the SQL query using execute() method.
cursor.execute ("Enter any MySQL query here. use the quotes. no semi-colon")
fetch a single row from query using fetchone() method.
row = cursor.fetchone ()
print(row)
fetch all the rest of the query using fetchall() method
data = cursor.fetchall()
print(data)
close the cursor object
cursor.close ()
close the connection
db.close ()

Related

python pypyodbc won't select data

I think I'm going mad here... again :). I'm trying to do the most simple thing on the planet and it doesn't work for some reason unknown to me. I have a python script that connects to a mssql database using pypyodbc and does stuff. when I insert data into the database, it works. when I try to extract it, it fails miserably. what am I doing wrong?
import pypyodbc as mssql
msConnErr = None
try:
msconn = mssql.connect('DRIVER={SQL Server};SERVER=server_name;DATABASE=database;TRUSTED_CONNECTION=True')
print('Source server connected')
srcCursor = msconn.cursor()
except:
print('Source server error')
msConnErr = True
srcCursor.execute("SELECT * FROM schema.table")
srcResult = srcCursor.fetchall()
print(srcResult)
the connection works as I'm being given a successful message. I can also see my script using sql server management studio being connected to the correct database, so I know I'm working in the right environment. the error I'm getting is:
UndefinedTable: relation "schema.table" does not exist
LINE 1: SELECT * FROM schema.table
the table exists, I must specify the schema as I have the same table name in different schemas (data lifecycle). I can extract data from it using sql server management studio, yet python fails miserably. it doesn't fail to insert 35 million rows in it using the same driver. no other query works, even SELECT ##VERSION fails, SELECT TOP (10) * FROM schema.table fails etc. ...
any ideas?
basically, I had a piece of code that would rewrite the srcCursor variable with another connection, obviously that relation wouldn't be present on another server. apologies!

sql INSERT in python (postgres, cursor, execute)

I had no problem with SELECTing data in python from postgres database using cursor/execute. Just changed the sql to INSERT a row but nothing is inserted to DB. Can anyone let me know what should be modified? A little confused because everything is the same except for the sql statement.
<!-- language: python -->
#app.route("/addcontact")
def addcontact():
# this connection/cursor setting showed no problem so far
conn = pg.connect(conn_str)
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
sql = f"INSERT INTO jna (sid, phone, email) VALUES ('123','123','123')"
cur.execute(sql)
return redirect("/contacts")
first look at your table setup and make sure your variables are named right in the right order, format and all that, if your not logging into the specific database on the sql server it won't know where the table is, you might need to send something like 'USE databasename' before you do your insert statement so your computer is in the right place in the server.
I might not be up to date with the language but is that 'f' supposed to be right before the quotes? if thats in ur code that'd probably throw an error unless it has a use im not aware of or its not relevant to the problem.
You have to commit your transaction by adding the line below after execute(sql)
conn.commit()
Ref: Using INSERT with a PostgreSQL Database using Python

python to call sql server procedure (2.7)

Never use python before, here want to using procedure already written in SQL server Script, then write a python application connect to database (already connected) rather than JAVA, because this is much easier.
Let user to give an input as the #Departments, then calculate the average of that Department's average salary.
My sql server procedure code:
CREATE PROC aaatest # Departments varchar(40)
AS
BEGIN
SELECT AVG(P.Salary)
FROM Company P
WHERE P.Department = #Departments
END
please write the a python application to get the input then pass to the #Departments. (conn = pymssql ... is already done!)
I guess this should give you some hint of how to script your requirement:
import pyodbc
cnxn=pyodbc.connect(r'Driver={SQL Server};Server=<servername>;Trusted_Connection;user=<username>;password=<password>',autocommit = True)
cursor=cnxn.cursor()
department=raw_input('Enter department:')
query='EXEC [master].[dbo].[aaatest] '+department+''
cursor.execute(query)
cnxn.close()

How to refresh django connection when inserting in SQL

I have the following pattern in my code:
cursor.execute("INSERT INTO main_catalog (1,'mark')")
conn.commit()
item = Catalog.objects.get(pk=1)
item.do_something()
However, I get an error saying that Catalog.DoesNotExist for id=1, even though I can see it in the database. How do I get the ORM to recognize this new value so I can then query it? (Note that I must use raw sql for certain reasons.)
As pointed out by #boxed, the accepted answer no longer works, however the close_old_connections() function he mentions worked for me. I.e.:
from django import db
db.close_old_connections()
The following pattern works to reset the connection and get a 'fresh cursor':
from django import db
try:
item = Catalog.objects.get(pk=1)
except Catalog.DoesNotExist:
db.close_connection()
item = Catalog.objects.get(pk=1)
This question may also be of use: Django multiprocessing and database connections.

Python MySQLdb, simple chatroom/guestbook app

I've browsed some of the other questions about MySQL and Python on SO. There are a few things eluding me, because I'm pretty new to Python.
First, I'm trying to get a simple guestbook app to work. It takes posted variables and puts them into a MySQL database. Take a look:
con = MySQLdb.connect (host = "localhost",
user = "Chat",
passwd = "myPass",
db = "Chatserver")
cursor = con.cursor()
cursor.execute ("INSERT INTO guestbook (name,message) VALUES(%s,%s)",(name,greeting))
Ok, so some of the tutorials and answers on SO have many Quotation marks surrounding the SQL query, and I don't know why that is. I've tried it with 1 quote, I've tried it with 3 quotes, and it just never works. There are no exception callbacks and the code seems to run, but no records are ever entered into the database.
So my two questions are, how many quotation marks do I need when encapsulating the Queries, and why doesn't my script add anything to the database but not report any errors?
Ok, this answer Can't execute an INSERT statement in a Python script via MySQLdb helped me figure it out.
You have to add this at the end of your query.
cursor.execute(...)
con.commit() //this is what makes it actually do the execution?

Categories