Python+mysql - building insert statements in for loop - python

The following prints the results properly but no records show up in the mysql table I'm attempting to populate:
#!/usr/bin/python
import MySQLdb
import string
db = MySQLdb.connect(host="localhost",
user="user",
passwd="******",
db="test")
cur=db.cursor()
i = 0
for lt in string.ascii_lowercase:
dbinsert = """insert into dns(domain,A,MX,T,serial,ttl)
values('"""+lt+""".com',' 1.1.1."""+str(i)+"""\\n','10 mx1.somehost.com.\\n',
'# "txt data"\\n',2013092001,300)"""
print dbinsert
i+=1
#cur=db.cursor()
try:
cur.execute(dbinsert)
db.commit
except MySQLdb.Error, e:
print e[0], e[1]
db.rollback()
db.close()
What am I missing here?

db.commit should be db.commit()

Related

Python array to mysql DB

Why i can't save a array list to mysql DB ^^.
This Script work
Code work:
########################################
# Importing modules
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="*******",
password="*********",
database="meineTestDB",
)
cursor = conn.cursor()
insert_stmt = (
"INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME)"
"VALUES (%s, %s)"
)
data = ('Test1', 'Test2')
try:
# Executing the SQL command
cursor.execute(insert_stmt, data)
# Commit your changes in the database
conn.commit()
except:
# Rolling back in case of error
conn.rollback()
print("Data inserted")
#Closing the connection
conn.close()
########################################
but i want save array to MySQL DB
I try | data = (cars1, cars2) | or | data = ((cars1), (cars2)) | but it doesn't work.
########################################
# Importing modules
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="*******",
password="*********",
database="meineTestDB",
)
cars1 = ["Ford", "Volvo", "BMW"]
cars2 = ["Ford", "Volvo", "BMW"]
cursor = conn.cursor()
insert_stmt = (
"INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME)"
"VALUES (%s, %s)"
)
data = (cars1, cars2)
try:
# Executing the SQL command
cursor.execute(insert_stmt, data)
# Commit your changes in the database
conn.commit()
except:
# Rolling back in case of error
conn.rollback()
print("Data inserted")
#Closing the connection
conn.close()
########################################
sry for this Symple question i'm new to that Space.
I hope you can help my.
THX for all answer.
It looks like your post is mostly code; please add some more details. 0.o

Rows are not getting inserted to mysql using python

I want to insert some records to mySQL database from PostgreSQL(both are remote servers),So i'm using the below script but the case is that the data is not getting inserted into MySQL database.
There is a final count statement which always results zero.May i know what could be the reason?
Also any improvement need to do on this code.
Suggestions please.
import psycopg2
import os
import time
#import MySQLdb
from mysql.connector import (connection)
import sys
#from pprint import pprint
#from datetime import datetime
#from psycopg2 import sql
#from utils.config import Configuration as Config
#from utils.postgres_helper import get_connection
#from utils.utils import get_global_config
def db_connect():
# MySQLdb connection
try:
source_host = 'magento'
#conf = get_global_config()
#cnx_msql = MySQLdb.connect(host=conf.get(source_host, 'host'),
#user=conf.get(source_host, 'user'),
#passwd=conf.get(source_host, 'password'),
#port=int(conf.get(source_host, 'port')),
#db=conf.get(source_host, 'db'))
cnx_msql = connection.MySQLConnection(host='server.com', user='db13009',passwd='fgDT***********',port=3306,db='db13009')
print('MySQL DB connected')
except mysql.connector.Error as e:
print ("MYSQL: Unable to connect!", e.msg)
sys.exit(1)
# Postgresql connection
try:
#cnx_psql = get_connection(get_global_config(), 'pg_dwh')
cnx_psql =psycopg2.connect(host='xxx.xxx.xx.xx',
dbname='postgres',
port='5432',
user='postgres',
password='*********')
print('PSQL DB connected')
except psycopg2.Error as e:
print('PSQL: Unable to connect!\n{0}').format(e)
sys.exit(1)
# Cursors initializations
cur_msql = cnx_msql.cursor()
cur_psql = cnx_psql.cursor()
SQL_test="""SELECT count(*) from action_status;"""
cur_msql.execute(SQL_test)
records = cur_msql.fetchall()
for row in records:
print("count = ", row[0], )
msql_command=""
try:
SQL_load="""SELECT created_at,payload from staging.sync;"""
msql_ins="""INSERT INTO action_status(payload,created_at)VALUES (%s, %s) """
cur_psql.execute(SQL_load)
for row in cur_psql:
try:
print(row[0])
print(row[1])
cur_msql.execute(msql_ins, row[0],row[1])
except psycopg2.Error as e:
print('ffffffffffffff')
print ("Cannot execute the query!!", e.pgerror)
sys.exit(1)
cnx_msql.commit()
cur_msql.execute(SQL_test)
records = cur_msql.fetchall()
for row in records:
print("count = ", row[0], )
except (Exception, psycopg2.Error) as error:
print ("Error while fetching data from PostgreSQL", error)
finally:
## Closing cursors
cur_msql.close()
cur_psql.close()
## Committing
cnx_psql.commit()
## Closing database connections
cnx_msql.close()
cnx_psql.close()
if __name__ == '__main__':
db_connect()
msql_ins is missing semicolon (not sure whether required or not). More importantly, you are missing a tuple; instead of:
cur_msql.execute(msql_ins, row[0],row[1])
try this instead:
cur_msql.execute(msql_ins, (row[0], row[1]))
Hope that helps :)

How to load pydev data to postgresql

My code functions. When running, it displays "Error %s % e" but when I go to postgresql the data doesn't upload there in anyway whatsoever. What should I do?
#!/usr/bin/python
# -*- coding: utf-8 -*-
import psycopg2
import sys
con = None
try:
con = psycopg2.connect("host='localhost' dbname='test123' user='postgres' password='XXX'")
cur = con.cursor()
cur.execute("CREATE TABLE Products(Id INTEGER PRIMARY KEY, Name VARCHAR(20), Price INT)")
cur.execute("INSERT INTO Products VALUES(1,'Milk',5)")
cur.execute("INSERT INTO Products VALUES(2,'Sugar',7)")
cur.execute("INSERT INTO Products VALUES(3,'Coffee',3)")
cur.execute("INSERT INTO Products VALUES(4,'Bread',5)")
cur.execute("INSERT INTO Products VALUES(5,'Oranges',3)")
con.commit()
except psycopg2.DatabaseError as e:
if con:
con.rollback()
print ("Error %s % e")
sys.exit(1)
finally:
if con:
con.close()
To start, your code should be formatted like this:
#!/usr/bin/python
-- coding: utf-8 --
import psycopg2
import sys
con = None
try:
con = psycopg2.connect("host='localhost' dbname='test123' user='postgres' password='XXX'")
cur = con.cursor()
cur.execute("CREATE TABLE Products(Id INTEGER PRIMARY KEY, Name
VARCHAR(20), Price INT)")
cur.execute("INSERT INTO Products VALUES(1,'Milk',5)")
cur.execute("INSERT INTO Products VALUES(2,'Sugar',7)")
cur.execute("INSERT INTO Products VALUES(3,'Coffee',3)")
cur.execute("INSERT INTO Products VALUES(4,'Bread',5)")
cur.execute("INSERT INTO Products VALUES(5,'Oranges',3)")
con.commit()
except psycopg2.DatabaseError as e:
if con:
con.rollback()
print ("Error %s % e")
sys.exit(1)
finally:
if con:
con.close()
if you're receiving the message "Error ..." then your code is not working as you expect it to. You should break it up into different sections or else manually run these commands in the Python terminal to debug where the issue is. - This is not really an answer, but hopefully we can work this one out since your question has not got enough information for an answer.. try running the following and see which error you hit:
#!/usr/bin/python
-- coding: utf-8 --
import psycopg2
import sys
try:
con = psycopg2.connect("host='localhost' dbname='test123' user='postgres' password='XXX'")
cur = con.cursor()
except Exception:
print("Failed to open a connection")
sys.exit(1)
try:
cur.execute("CREATE TABLE Products(Id INTEGER PRIMARY KEY, Name
VARCHAR(20), Price INT)")
cur.execute("INSERT INTO Products VALUES(1,'Milk',5)")
cur.execute("INSERT INTO Products VALUES(2,'Sugar',7)")
cur.execute("INSERT INTO Products VALUES(3,'Coffee',3)")
cur.execute("INSERT INTO Products VALUES(4,'Bread',5)")
cur.execute("INSERT INTO Products VALUES(5,'Oranges',3)")
con.commit()
except Exception as e:
print("Failed to insert data into the database")
sys.exit(1)

pydev data not uploading on postgres

My code functions and indentations are correct on eclipse. When running, it displays "Error %s % e" but when I go to postgresql the data doesn't upload there in anyway whatsoever. What should I do?
#!/usr/bin/python
# -*- coding: utf-8 -*-
import psycopg2
import sys
con = None
try:
con = psycopg2.connect("host='localhost' dbname='test123' user='postgres' password='XXX'")
cur = con.cursor()
cur.execute("CREATE TABLE Products(Id INTEGER PRIMARY KEY, Name VARCHAR(20), Price INT)")
cur.execute("INSERT INTO Products VALUES(1,'Milk',5)")
cur.execute("INSERT INTO Products VALUES(2,'Sugar',7)")
cur.execute("INSERT INTO Products VALUES(3,'Coffee',3)")
cur.execute("INSERT INTO Products VALUES(4,'Bread',5)")
cur.execute("INSERT INTO Products VALUES(5,'Oranges',3)")
con.commit()
except psycopg2.DatabaseError as e:
if con:
con.rollback()
print ("Error %s % e")
sys.exit(1)
finally:
if con:
con.close()

Python Not inserting into MySQL

import MySQLdb
import time
try:
db = MySQLdb.connect(host="", #your host, usually localhost
user="", #your username
passwd="", #your password
db="") #name of the data base
cur = db.cursor()
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
SQL = "INSERT INTO TBL_PYTest (Time) VALUES (%s)"
Count = 0
while Count < 5:
UTime = int(time.time())
print UTime
cur.execute(SQL, (UTime))
time.sleep(5)
Count = Count + 1
print Count
Why isn't this working? its printing correctly but the database stays empty.
Ive checked the DB and it seems fine
All the details are correct
You would need to commit your transaction , or set autocommit as True.

Categories