Tuesday, March 7, 2017

Python MySQL Database Connection using ODBC

I'm posting a sample python to Sql Server connection code. Here i will be using Python 2.7.

1. pip install pyodbc

2. Install the MySQL ODBC Connector from here.

3.  Setup ODBC connection details in Control Panel --> Admin Tools --> System DSN




4. Code :

from os import getenv
import pyodbc

conn = pyodbc.connect(r'Driver={MySQL ODBC 5.3 ANSI Driver};Server=127.0.0.1;Database=test;Trusted_Connection=yes;')

cur = conn.cursor()
string = "CREATE TABLE IF NOT EXISTS TestTable(empname varchar(15), sal double)"
cur.execute(string)

sqlStatement = "INSERT INTO TestTable(empname,sal)  VALUES (?, ?)"

cur.execute(sqlStatement, ('chandan', '1000'))

conn.commit()

4.Run python code.py in CMD



No comments:

Post a Comment