Print Data from MySQL Database to Console from Python - python

I'm using Visual Studio 2017 with a Python Console environment. I have a MySQL database set up which I can connect to successfully. I can also Insert data into the DB. Now I'm trying to display/fetch data from it.
I connect fine, and it seems I'm fetching data from my database, but nothing is actually printing to the console. I want to be able to fetch and display data, but nothing is displaying at all.
How do I actually display the data I select?
#importing module Like Namespace in .Net
import pypyodbc
#creating connection Object which will contain SQL Server Connection
connection = pypyodbc.connect('Driver={SQL Server};Server=DESKTOP-NJR6F8V\SQLEXPRESS;Data Source=DESKTOP-NJR6F8V\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False')
cursor = connection.cursor()
SQLCommand = ("SELECT ID FROM MyAI_DB.dbo.WordDefinitions WHERE ID > 117000")
#Processing Query
cursor.execute(SQLCommand)
#Commiting any pending transaction to the database.
connection.commit()
#closing connection
#connection.close()

I figured it out. I failed to include the right Print statement. Which was:
print(cursor.fetchone())
I also had the connection.commit statement in the wrong place (it was inserted even executing the Print statement). The final code that worked was this:
#importing module Like Namespace in .Net
import pypyodbc
#creating connection Object which will contain SQL Server Connection
connection = pypyodbc.connect('Driver={SQL Server};Server=DESKTOP-NJR6F8V\SQLEXPRESS;Data Source=DESKTOP-NJR6F8V\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False')
cursor = connection.cursor()
SQLCommand = ("SELECT * FROM MyAI_DB.dbo.WordDefinitions")
#Processing Query
cursor.execute(SQLCommand)
#Commiting any pending transaction to the database.
print(cursor.fetchone())
connection.commit()
#closing connection
#connection.close()

Related

How to Make SQL Table Show on Pycharm

I have a postgres db running on docker. I am able to access this db via my sql client Dbeaver and when I run select statements I see the expected results.
I would like to be able to query this db via a Python script and after some searching found psycopg2 package.
When I run the code below it 'looks' like it's successful, the conn and cursor objects appear as a variables.
import pandas as pd
import psycopg2
# connect to db
conn = psycopg2.connect(
host="localhost",
database="postgres",
user="postgres",
password="example")
# create a cursor
cur = conn.cursor()
However, when trying to query the db using cur.connect(), , variable ex_data is None. This exact same query via my sql client returns a table of data.
ex_data = cur.execute('select * from myschema.blah limit 10;')
How can I query my db via Python using psycopg2? Desired result wold be a data frame with the result set from the query string above.

"Invalid cursor state" error when executing a batch that includes a USE statement

I tried retrieving data from a Microsoft SQL database using pypyodbc 1.3.3 with Python 3.5 on Windows but got a pypyodbc.ProgrammingError '[24000] [Microsoft] [SQL Server Native Client 11.0] Invalid cursor state' using the following code:
import pypyodbc
conn = pypyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};SERVER=server;DATABASE=database;UID=uid;PWD=pwd')
cursor = conn.cursor()
sql = '''USE database;
SELECT R0
FROM table;'''
cursor.execute(sql)
results = cursor.fetchone()
print(results)
The SQL works in Microsoft SQL Server Management Studio, the connection and executing worked in another script i wrote to insert into the same database and also works if i remove
results = cursor.fetchone()
So far I tried cursor.fetchone(), cursor.fetchall() and list(cursor) but all produced the same result which leads me to believe that the command itself isn't the problem.
According to this microsoft site it means that there isn't an open cursor, but I can get it's description, so from my understanding there has to be.
It's not a matter of being unable to execute a USE ... statement at all, it's just that we cannot do that as part of a multi-statement batch. So, this will not work ...
crsr.execute("""\
USE master;
SELECT TOP 2 name FROM sys.tables ORDER BY name;
""")
rows = crsr.fetchall() # error
... but this will work fine
crsr.execute("USE master")
crsr.execute("SELECT TOP 2 name FROM sys.tables ORDER BY name")
rows = crsr.fetchall()
(Tested with both pypyodbc 1.3.4 and pyodbc 4.0.21)
I had a similar issue. I was able to resolve this by removing the "USE Database" statement.
You already connected to your db here:
conn = pypyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};SERVER=server;DATABASE=database;UID=uid;PWD=pwd')

pyodbc is not updating table

Basically I'm trying to update Column1_mbgl field data in Table1, all based in MS Access database. The script gets executed without any errors, but when the table is checked no update occurred. I have tried two options as shown in the code without any success. The second option is the SQL code generated directly from MS Access query. Can anybody suggest what I'm missing in the code?
#import pypyodbc
import pyodbc
# MS ACCESS DB CONNECTION
pyodbc.lowercase = False
conn = pyodbc.connect(
r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
r"Dbq=C:\temp\DB_access.accdb;")
# OPEN CURSOR AND EXECUTE SQL
cur = conn.cursor()
# Option 1 - no error and no update
cur.execute("UPDATE Table1 SET Column1_mbGL = Column2_mbGL-0.3 WHERE ((Column3_name='PZ01') AND (DateTime Between #6/14/2016 14:0:0# AND #6/16/2016 12:0:0#) AND (TYPE='LOG'))");
# Option 2 - no error and no update
#cur.execute("UPDATE Table1 SET Table1.Column1_mbGL = [Table1]![Column2_mbGL]-0.3 WHERE (((Table1.Column3_name)='PZ01') AND ((Table1.DateTime) Between #6/14/2016 14:0:0# And #6/16/2016 12:0:0#) AND ((Table1.TYPE)='LOG'))");
cur.close()
conn.close()
You forgot to conn.commit() after executing your UPDATE query. The Python database API specifies that connections open with "autocommit" off by default, so an explicit commit is needed.

Empty table in MySQL even though Python can insert data into table

I'm new to mySQL and Python.
I have code to insert data from Python into mySQL,
conn = MySQLdb.connect(host="localhost", user="root", passwd="kokoblack", db="mydb")
for i in range(0,len(allnames)):
try:
query = "INSERT INTO resumes (applicant, jobtitle, lastworkdate, lastupdate, url) values ("
query = query + "'"+allnames[i]+"'," +"'"+alltitles[i]+"',"+ "'"+alldates[i]+"'," + "'"+allupdates[i]+"'," + "'"+alllinks[i]+"')"
x = conn.cursor()
x.execute(query)
row = x.fetchall()
except:
print "error"
It seems to be working fine, because "error" never appears. Instead, many rows of "1L" appear in my Python shell. However, when I go to MySQL, the "resumes" table in "mydb" remains completely empty.
I have no idea what could be wrong, could it be that I am not connected to MySQL's server properly when I'm viewing the table in MySQL? Help please.
(I only use import MySQLdb, is that enough?)
use commit to commit the changes that you have done
MySQLdb has autocommit off by default, which may be confusing at first
You could do commit like this
conn.commit()
or
conn.autocommit(True) Right after the connection is created with the DB

Python not inserting data's into mysql

I am testing Python and Mysql in that i am able to create and delete table's but i am unable to insert data in them.I searched stackoverflow and mostly they suggest to use
commit()
So i used it and even after i used the data is not inserted into the database.Please help me.
This is the code i use it creates the table but not inserting data
import MySQLdb
db = MySQLdb.connect("localhost","user","password")
cxn = MySQLdb.connect(db='test')
cursor = cxn.cursor()
cursor.execute("CREATE TABLE users(name VARCHAR(40),id VARCHAR(40))")
cursor.execute("INSERT INTO users(name,id) VALUES('John','1')")
db.commit()
print "Opertion completed successfully"
Are db and cxn connections to the same database?
You should establish your connection using following:
db = MySQLdb.connect(host="localhost",
db="test",
user="user",
passwd="password")
The cursor should then be derived from this connection via:
cursor = db.cursor()
I would hazard that your issue is coming from the ambiguity between db and cxn.

Categories