inserting into a database (mysql) via a python program [duplicate] - python

This question already has answers here:
How do I connect to a MySQL Database in Python?
(26 answers)
Closed 5 years ago.
i am familiar with python and also familiar with mysql and SQL. I am also clear on con, cur and commit, but my problem here is that im trying to make a small program in python (no need for a gui) to insert data into a mysql database, and bring it on my console or file. I'm confused where to start, i tried seeking google but i couldn't find any toturials about my issue, any help? a link or where to start. Also:
i know the python program can be written in an IDE or a text file, but how does it connect to mysql database? if im wrong please correct me.

SQLAlchemy is good: https://www.sqlalchemy.org/
Otherwise, using the conn/cur as you described is easy: https://www.tutorialspoint.com/python/python_database_access.htm

Go though the documentation to get yourself familiar with python, mysql and how to work with them together.
Although, the minimal code would look something like this :
import MySQLdb
query = "insert into DB_NAME values (1,2)"
try :
conn = MySQLdb.connect(host="",
user="",
passwd="",
db="")
cursor = conn.cursor()
cursor.execute(query)
conn.commit()
cursor.close()
conn.close()
except (MySQLdb.Error, Exception) as error :
print error
print "Insert data unsuccessful"

See the code below
import mysql.connector
from mysql.connector import MySQLConnection, Error
class SQL_Connect:
def __init__(self):
#-------------------------------------------------------
# Database Connection Param's
self.host_Address = 'Host Here'
self.database_Name = 'Database Name'
self.userName = 'User Name'
self.db_Password = 'Password'
#-------------------------------------------------------
def insert_IntoDB(self, Manufacturer, partNum, formFactor, socket, chipSet, memSlots, memType, maxMem, raidSup, onboardVid, crosFire_Sup, sli_Sup, sata6GBS, sataExpress, onboard_Ether):
test_Query = 'INSERT INTO motherboards (Manufacturer, modelNum, formFactor, socket, chipset, memSlots, memType, maxMem, raidSup, onboardVid, crosfireSup, sliSup, sata6GBS, sataExpress, onboardEther) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
args = (Manufacturer, partNum, formFactor, socket, chipSet, memSlots, memType, maxMem, raidSup, onboardVid, crosFire_Sup, sli_Sup, sata6GBS, sataExpress, onboard_Ether)
try:
conn = mysql.connector.connect(host = self.host_Address, database = self.database_Name, user = self.userName, password = self.db_Password)
if conn.is_connected():
print 'MySQL Database Connection Established'
cursor = conn.cursor()
cursor.execute(test_Query, args)
conn.commit()
print 'Data Inserted!!!'
except Error as e:
print ('ERROR: ',e)
finally:
cursor.close()
conn.close()

Related

Error Importing Excel Data into MySQL using Python

I am trying to get data from an excel spreadsheet into a MySQL database using Python. I can do it fine if add my records to a list of tuples manually in my SQL query, but trying to loop through the records I get an error stating the tuple index out of range. Not sure what the issue is here and how to remedy it. Any help would be appreciated. Thank you.
Picture is attached for code and error messages. ErrorMSG PythonCode
import mysql.connector
import xlrd
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
passwd = "*******",
database = "testdb",
)
mycursor = mydb.cursor()
loc=("E:\\SOX Reports\\2021 Reports\\populateData.xlsx")
l=list()
a=xlrd.open_workbook(loc)
sheet=a.sheet_by_index(0)
sheet.cell_value(0,0)
for i in range (1,418):
l.append(tuple(sheet.row_values(i)))
addRows = "insert into emplist (ID,SITE, OU, firstName) values(%s,%s,%s,%s)"
mycursor.executemany(addRows,l)
mydb.commit()
mydb.close()

How to use a external variable into a SQL query's where condition?

I want to fetch data from PostgreSQL database through python script. In where condition I have to use a value from local variable called "lastrun" last run is nothing but I have stored the last time when the program gets executed in a file. After read that file I stored that value in a variable called "lastrun" and I wanna use it in the query.
lastrun="06/11/2020 08:20:50.949881"
def doQuery( conn ):
cur = conn.cursor()
cur.execute("SELECT accountno,req, type, site,ref FROM accounts WHERE created > lastrun")
records=cur.fetchall()
print("Using PyGreSQL…")
import pgdb
myConnection = pgdb.connect( host=hostname, user=username, password=password, database=database )
doQuery( myConnection )
myConnection.close()
I tried but nothing works for me. Please help me out.
Thanks in advance.
you can use python string formatting to achive this
lastrun="06/11/2020 08:20:50.949881"
def doQuery( conn ):
cur = conn.cursor()
cur.execute("SELECT accountno,req, type, site,ref FROM accounts WHERE created > '%s'"%lastrun)
records=cur.fetchall()
print("Using PyGreSQL…")
import pgdb
myConnection = pgdb.connect( host=hostname, user=username, password=password, database=database )
doQuery( myConnection )
myConnection.close()
for more info visit here.

MySQL python connector code aborts without error (Code from the MySQL documentation)

I was trying to use the python connector code given in the MySQL documentation and test it on a small database already created, but it aborts. The code is just supposed to connect to the db and add a new email adress.
import mysql.connector
from mysql.connector import errorcode
cnx = mysql.connector.connect(user='root', password='pwd', host='localhost', database='db')
cursor = cnx.cursor()
add_email = ("INSERT INTO employee(MID, Email) VALUES (%s,%s)")
email_details = (NULL, "a#a.de")
cursor.execute(add_email, email_details)
cnx.commit()
input("data entered successfully")
cnx.close()
By setting breakpoints I found out that the problem probably lies in the cursor.execute() statement. (I used Null as the first %s since MID is Auto Incrementing btw)
To solve this problem NULL (for the autoincrementing "MID") needs to be replaced with None.

Connect python to Sybase IQ

First of all thank you for your help.
I was trying to retrieve some data from a sybase IQ database using python, but I can not make it.
I've tried with the following code( from https://github.com/sqlanywhere/sqlanydb):
import sqlanydb
conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo' )
curs = conn.cursor()
curs.execute("select 'Hello, world!'")
print( "SQL Anywhere says: %s" % curs.fetchone() )
curs.close()
conn.close()
Unfotunately it gives me the following error:
InterfaceError: ('Could not load dbcapi. Tried: None,dbcapi.dll,libdbcapi_r.so,libdbcapi_r.dylib', 0)
Does anyone know how to fix it?
Thanks in advance
Jessica
On windows, first you need to add the data source name (DSN).
You do this by searching for 'odbc data source administrator' on windows and creating a DSN for 'SQL Anywhere 12'. Fill in the necessary information like username,password,host,port,server name and database name. Finally test the connection as shown.
Once finished you can call the code as follows:
import sqlanydb
conn = sqlanydb.connect(dsn='SYBASE_IQ')
curs = conn.cursor()
curs.execute("select 'Hello, world!'")
print( "SQL Anywhere says: %s" % curs.fetchone())
curs.close()
conn.close()
Get and install the SYBASE ODBC DRIVER.
Configure the DSN on your PC.
On Windows, search for the Microsoft ODBC Administrator. Then create a DSN.
Python code:
using SQLAchemy
import sqlalchemy as sa
from sqlalchemy import create_engine, event
from sqlalchemy.engine.url import URL
import urllib
params = urllib.parse.quote_plus('DSN=dsn_name;PWD=user_pwd')
engine = sa.create_engine("sybase+pyodbc:///?odbc_connect={}".format(params))
with engine.connect() as cursor:
cursor.execute(""" SELECT * FROM database """)
Using PyODBC
import pyodbc
conn = pyodbc.connect('DSN=dsn_name;PWD=user_pwd')
with conn:
cursor = conn.cursor()
cursor.execute(""" SELECT * FROM database """)

Python psycopg2 Execute Hangs

I am using Python 3.x within an app hosted on Heroku with Basic PostgreSQL instance and Im using the psycopg2 library (as "lite")
Recently started hanging when I call Execute on the cursor object.
I am not sure how to troubleshoot this and would appreciate any thoughts.
Here is how I instantiate Connection:
def getConnection():
urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse(os.environ["HEROKU_STUFF_HERE"])
con = lite.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
return con
Here is how I generally execute non-return type statements:
def ExecuteSQL(sql):
con = DB.getConnection()
with con:
cur = con.cursor()
print("In")
cur.execute(sql)
print("out")
The app NEVER sees the light after printing the word "In" to the console.
I've left try except blocks out intentionally so as to blow the thing up.....no dice.
pretty much doesnt matter what the SQL Statement is, I get the same result
Running the same sql in a sql client tool executes instantly.
Im also not sure how to detect if this statement even makes it into Postgresql.....
Thanks for any help you can offer
psycopg2 opened the transaction which is not closed until a commit() or rollback(). Therefore your changes were not persistent (docs).
def ExecuteSQL(sql):
con = DB.getConnection()
with con:
cur = con.cursor()
cur.execute(sql)
con.commit()
or you could just do the following:
def ExecuteSQL(sql):
con = DB.getConnection()
with con:
con.autocommit = True
cur = con.cursor()
cur.execute(sql)

Categories