Python MySQL Long Query Insert or Update - python

Im trying to insert / update a very long sql, tried to format to string, but wont take any effect on MySQL table:
import MySQLdb
db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
cur = db.cursor()
str1 = 'x'
str2 = 'y'
s = """a:150:{i:0;b:0;s:12:"social_icons";a:9:{s:8:"facebook";s:1:"1";s:7:"twitter";s:1:"1";s:5:"email";s:1:"1";s:9:"pinterest";s:1:"1";s:10:"googleplus";s:1:"1";s:8:"linkedin";s:1:"0";s:2:"vk";s:1:"0";s:6:"tumblr";s:1:"0";s:8:"whatsapp";s:1:"0";}s:7:"backups";N;s:9:"smof_init";s:31:"Tue, 16 Aug 2016 23:03:59
+0000";s:17:"minified_flatsome";i:0;s:16:"flatsome_builder";i:1;s:13:"flatsome_docs";i:1;s:16:"maintenance_mode";i:0;s:21:"maintenance_mode_text";s:24:"Please check back soon..";s:19:"html_scripts_header";s:0:"";s:19:"html_scripts_footer";s:0:"";s:15:"html_custom_css";s:6:"div {}";s:22:"html_custom_css_mobile";s:0:"";s:9:"site_logo";s:57:"[site_url]/wp-content/uploads/2016/08/Logomakr_8dvMrU.png";s:0:"";s:165:"Favicon upload has moved to: <br/> <a href=''[site_url]/wp-admin/customize.php?&autofocus%5Bpanel%5Dof-option-logoandicons''>Appearance
> Customize > Site Identity</a>";s:16:"custom_cart_icon";s:0:"";s:14:"site_logo_dark";s:0:"";s:16:"site_logo_sticky";s:0:"";s:11:"body_layout";s:10:"full-width";s:10:"box_shadow";i:0;s:7:"body_bg";s:0:"";s:13:"body_bg_image";s:0:"";s:12:"body_bg_type";s:12:"bg-full-size";s:13:"content_color";s:5:"light";s:10:"content_bg";s:4:"#FFF";s:13:"header_preset";s:0:"";s:13:"header_height";s:3:"120";s:10:"logo_width";s:3:"210";s:13:"logo_position";s:6:"center";s:10:"search_pos";s:4:"left";s:12:"nav_position";s:3:"top";s:8:"nav_size";s:3:"80%";s:18:"myaccount_dropdown";i:1;s:19:"account_login_style";s:4:"link";s:9:"show_cart";i:1;s:14:"top_right_text";s:0:"";s:13:"header_sticky";i:1;s:20:"header_height_sticky";s:2:"70";s:12:"header_color";s:5:"light";s:9:"header_bg";s:4:"#fff";s:13:"header_bg_img";s:0:"";s:17:"header_bg_img_pos";s:8:"repeat-x";s:11:"topbar_show";i:1;s:9:"topbar_bg";s:0:"";s:11:"topbar_left";s:0:"";s:12:"topbar_right";s:0:"";s:15:"nav_position_bg";s:4:"#eee";s:18:"nav_position_color";s:5:"light";s:17:"nav_position_text";s:0:"";s:21:"nav_position_text_top";s:0:"";s:17:"html_after_header";s:0:"";s:10:"html_intro";s:0:"";s:16:"footer_left_text";s:158:"Copyright [ux_current_year] © <strong>asd.com</strong>.<br> <img src=''http://www.aasd.com/wp-content/uploads/2015/12/creditcard-icons.png''>";s:17:"footer_right_text";s:137:"<img src="http://gninggel.com/wp-content/uploads/2016/08/comodo_secure_seal_100x85_transp.png"><br> %s <br>%s";s:14:"footer_1_color";s:5:"light";s:17:"footer_1_bg_color";s:7:"#ff3233";s:17:"footer_1_bg_image";s:0:"";s:16:"footer_1_columns";s:7:"large-3";s:14:"footer_2_color";s:4:"dark";s:17:"footer_2_bg_color";s:7:"#772222";s:17:"footer_2_bg_image";s:0:"";s:16:"footer_2_columns";s:7:"large-3";s:19:"footer_bottom_style";s:4:"dark";s:19:"footer_bottom_color";s:4:"#333";s:18:"html_before_footer";s:0:"";s:17:"html_after_footer";s:0:"";s:13:"disable_fonts";i:0;s:13:"type_headings";s:4:"Lato";s:10:"type_texts";s:4:"Lato";s:8:"type_nav";s:4:"Lato";s:8:"type_alt";s:14:"Dancing Script";s:11:"type_subset";a:7:{s:5:"latin";s:1:"1";s:12:"cyrillic-ext";s:1:"0";s:9:"greek-ext";s:1:"0";s:5:"greek";s:1:"0";s:10:"vietnamese";s:1:"0";s:9:"latin-ext";s:1:"0";s:8:"cyrillic";s:1:"0";}s:11:"custom_font";s:0:"";s:13:"color_primary";s:7:"#dd3333";s:15:"color_secondary";s:7:"#eeee22";s:13:"color_success";s:7:"#7a9c59";s:11:"color_links";s:0:"";s:13:"button_radius";s:3:"0px";s:15:"dropdown_border";s:0:"";s:11:"dropdown_bg";s:0:"";s:13:"dropdown_text";s:5:"light";s:11:"blog_layout";s:13:"right-sidebar";s:10:"blog_style";s:11:"blog-normal";s:18:"blog_archive_title";i:1;s:11:"blog_header";s:1:" ";s:15:"blog_after_post";s:1:" ";s:16:"blog_post_layout";s:13:"right-sidebar";s:15:"blog_post_style";s:7:"default";s:15:"blog_author_box";i:1;s:10:"blog_share";i:0;s:13:"blog_parallax";i:0;s:19:"featured_items_page";i:0;s:22:"featured_items_pr_page";s:2:"12";s:22:"featured_items_related";s:7:"default";s:29:"featured_items_related_height";s:5:"250px";s:16:"wc_account_links";i:1;s:14:"facebook_login";i:0;s:17:"facebook_login_bg";s:0:"";s:14:"color_checkout";s:0:"";s:10:"color_sale";s:0:"";s:16:"color_new_bubble";s:7:"#7a9c59";s:12:"color_review";s:0:"";s:15:"product_sidebar";s:12:"left_sidebar";s:25:"product_offcanvas_sidebar";s:1:"0";s:15:"product_display";s:4:"tabs";s:18:"cart_dropdown_show";s:1:"1";s:16:"shop_aside_title";s:0:"";s:12:"product_zoom";s:1:"0";s:16:"related_products";s:6:"slider";s:23:"related_products_pr_row";s:1:"4";s:20:"max_related_products";s:2:"12";s:15:"disable_reviews";s:1:"0";s:9:"tab_title";s:0:"";s:11:"tab_content";s:0:"";s:23:"html_before_add_to_cart";s:1:" ";s:22:"html_after_add_to_cart";s:0:"";s:14:"html_shop_page";s:0:"";s:16:"category_sidebar";s:12:"left-sidebar";s:10:"grid_style";s:5:"grid1";s:10:"grid_frame";s:6:"normal";s:12:"masonry_grid";s:1:"0";s:16:"add_to_cart_icon";s:7:"disable";s:25:"short_description_in_grid";s:1:"0";s:9:"cat_style";s:10:"text-badge";s:15:"breadcrumb_size";s:17:"breadcrumb-normal";s:15:"breadcrumb_home";s:1:"1";s:18:"category_row_count";s:1:"3";s:25:"category_row_count_mobile";s:1:"2";s:16:"products_pr_page";s:2:"12";s:13:"search_result";s:1:"0";s:13:"product_hover";s:12:"fade_in_back";s:12:"bubble_style";s:6:"style1";s:22:"sale_bubble_percentage";s:1:"0";s:18:"disable_quick_view";s:1:"0";s:13:"wishlist_icon";s:5:"heart";s:15:"coupon_checkout";s:1:"0";s:17:"continue_shopping";s:1:"0";s:16:"html_cart_footer";s:0:"";s:21:"html_checkout_sidebar";s:0:"";s:14:"html_thank_you";s:0:"";s:12:"catalog_mode";s:1:"0";s:19:"catalog_mode_prices";s:1:"0";s:19:"catalog_mode_header";s:0:"";s:20:"catalog_mode_product";s:0:"";s:21:"catalog_mode_lightbox";s:0:"";s:19:"facebook_login_text";s:0:"";s:23:"facebook_login_checkout";s:1:"1";s:18:"custom_share_icons";s:0:"";s:18:"nav_menu_locations";a:3:{s:7:"primary";i:11;s:14:"primary_mobile";i:11;s:6:"footer";i:12;}s:18:"custom_css_post_id";i:-1;}
""" % (str1, str2)
cur.execute("INSERT INTO `wp_options`(`option_id`, `option_name`, `option_value`, `autoload`) VALUES ('450', 'theme_mods_flatsome', '%s', 'yes')" % s)
db.commit()
Also tried with ( ) instead of """ and with """, but nothing.
There is no error message, seems query is okay, but won`t change nothing.
Made a new file to try to load the string from file
with open('config') as f:
query = f.read()
cur.execute("UPDATE wp_options SET option_value = '%s' WHERE option_id = 450" % query)

The problem was with encoding, I had several hours of headache cause of this but I`m back to share the resolution:
str = unicode(str, errors='ignore')

Related

Transfering Data in MS Access Using Python

I have an ever growing and changing database that reflects a permits passed by the State and EPA.
As the database changes and updates I need to transfer the relevant information.
The script does two things; first it checks which fields are the same and creates a list of fields and data that will be inserted into the new database. Second to insert the data into the new database.
Problem is I cannot get it to insert. I have matched everything like it says online in various ways but i get error ('42000', '[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement. (-3502) (SQLExecDirectW)').
I cannot figure out how to prevent it.
Code:
import pyodbc
importDatabase = r"J:\ENVIRO FIELD\AccessDatabases\MS4\MS4 Town Databases\~Template\MS4_Apocalypse Import DEV 1.accdb"
"Create the Import Database Connection"
connectionImport = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s;' %(importDatabase))
cursorImport = connectionImport.cursor()
"####---Outfall Section---####"
"Import the outfall names into the new database"
tbl = "tbl_Outfall_1_Profile"
exportList = []
importList = []
for row in cursorImport.columns(table = "tblExportMigration_Outfall_1_Profile"):
field = row.column_name
exportList.append(field)
for row in cursorImport.columns(table = "tbl_Outfall_1_Profile"):
field = row.column_name
importList.append(field)
matchingList = []
for field in exportList:
if field != "outfallID":
if field in importList:
matchingList.append(field)
else:
continue
sqlValue = ""
for field in matchingList:
sqlValue += "[%s], " %(field)
sqlValue = sqlValue[:-2]
sql = "SELECT %s from %s" %(sqlValue, "tblExportMigration_Outfall_1_Profile")
for rowA in cursorImport.execute(sql):
tupleList = list(rowA)
tupleList = ["" if i == None else i for i in tupleList]
tupleValues = tuple(tupleList)
sqlUpdate = """INSERT INTO tbl_Outfall_1_Profile (%s) Values %s;""" %(sqlValue, tupleValues)
cursorImport.execute(sqlUpdate)
cursorImport.close()
This is the sql string I create
"INSERT INTO tbl_Outfall_1_Profile ([profile_OutfallName], [profile_HistoricalName1], [profile_HistoricalName2], [profile_HistoricalName3], [profile_HistoricalName4]) Values ('756', '', '', '', '');"
Taking what #Gord Thompson said I was actually able to create a dynamic parameter flow
First created a module to create the ?
def Defining_Paramters(length):
parameterString = ""
for x in range(1,length):
parameterString += "?, "
parameterString += "?"
return parameterString
Then stuck it into the string for the sql update
sqlUpdate = sqlUpdate = "INSERT INTO %s (%s) Values (%s);" %(table, sqlFrameworkSubStr, parameters)
Run the cursor and commit it
cursorTo.execute(sqlUpdate, (dataTuple))
connectionTo.commit()
It would seem that you have to create the query in its entirety then have your data in tuple format for entry
This is the sql string [I think] I create
Try this:
sqlUpdate = """INSERT INTO tbl_Outfall_1_Profile (%s) Values (%s);""" %(sqlValue, tupleValues)
or perhaps:
sqlUpdate = "INSERT INTO tbl_Outfall_1_Profile (%s) Values (%s);" %(sqlValue, tupleValues)

Error: can only concatenate str (not "list") to str

I am trying to import txt file into sql, but i have an error:
TypeError: can only concatenate str (not "list") to str
My code:
import psycopg2
con = psycopg2.connect(
host = "",
database="",
user = "",
password = "")
cursor = con.cursor()
with open("pom1.txt") as infile:
for line in infile:
data = line.split()
print(data)
query = ("INSERT INTO Pomiary_Obwod_90(Znacznik, Pomiar_x, Pomiar_y, Pomiar_z) VALUES"
"(" + data + ");")
cursor.execute(query, *data)
con.commit()
Does anyone have an idea how can i solve it? :)
You don't put the actual values into the parameterized query; you put whatever placeholders are appropriate for your library.
data = line.split()
place_holders = ', '.join("%s" for _ in data) # Assuming %s is correct
query = ("INSERT INTO Pomiary_Obwod_90(Znacznik, Pomiar_x, Pomiar_y, Pomiar_z) VALUES"
"(" + place_holders + ");")
cursor.execute(query, *data)
cursor.execute takes care of inserting each value where a placeholder occurs, ensure things are properly quoted/escaped/etc.
There are several problems here. First, as the error says, you are trying to concatenate a List (which is data) directly to a string.
Second, you should not use + to concatenate your values and your query.
The doc says:
Warning: Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.
You should only pass the values to the query via %s.
I'm not sure about the use of * in front of data in cursor.execute(query, *data).
Here is a code that should work, though I have nothing at hand for testing it right now:
import psycopg2
con = psycopg2.connect(
host = "",
database="",
user = "",
password = "")
cursor = con.cursor()
with open("pom1.txt") as infile:
for line in infile:
data = line.split()
print(data)
query = ("INSERT INTO Pomiary_Obwod_90(Znacznik, Pomiar_x, Pomiar_y, Pomiar_z) VALUES (%s, %s, %s, %s);")
cursor.execute(query, data)
con.commit()

Read from csv file and put to Mysql with different field type using python

i have table field of "datetime", "integer", "double", "string (varchar)" type in Mysql, how can i convert from string (from csv file) to each type of Mysql field using python ? example of my csv file :
EURUSD;M5;2011.01.05 02:10:00;1.33193;1.33193;1.33112;1.33135;0;-1;0;0;1.33215
My python code is like this :
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","me","xxxxx","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
inputFile = "source.csv"
with open(inputFile, 'r') as fr:
data = fr.readlines()
for line in data:
words = line.strip().split(";")
getpair = words[0]
gettf = words[1]
gettime = (datetime) words[2]
getopen = (double) words[3]
gethigh = (double) words[4]
getlow = (double) words[5]
getclose = (double) words[6]
getcUpdown = (int) words[7]
getfractal = (int) words[8]
getzzId = (int) words[9]
getzzUpdown = (int) words[10]
getzzEndPrc = (double) words[11]
print(getpair,"=",gettf,"=",gettime,"=",getopen,"=",gethigh,"=",getlow,"=",getclose,"=",getcUpdown,"=",getfractal,"=",getzzId,"=",getzzUpdown,"=",getzzEndPrc)
# =====================================================================
# Prepare SQL query to INSERT a record into the database.
sql = '''INSERT INTO `mytable` (pair,timeframe,time,open,close,high,low,updown,fractal,zzid,zzupdown,zzlength) \
VALUES (getpair,gettf,gettime,getopen,getclose,gethigh,getlow,getcUpdown,getfractal,getzzId,getzzUpdown,getzzEndPrc)'''
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
fr.close()
Thanks
p
Type conversion in Python is done by:
int(words[7])
not
(int)words[7]
There is no double type in Python. Use float instead.
You can not convert directly to datetime. Use datetime.strptime() to parse the input string:
from datetime import datetime
gettime = datetime.strptime(words[2], '%Y.%m.%d %H:%M:%S')
You might not need to do this (conversion should be handled when using parameterised queries - see below), but you can convert that to a string format that MySQLDB supports. You can use strftime() for that:
gettime = gettime.strftime('%Y-%m-%d %H:%M:%S')
The sql query string needs to substitute the the actual values. Your
query is inserting the names of the variables, not the
values. You can (and should) use a parameterised query like this:
sql = 'INSERT INTO `mytable` (pair, timeframe, time, open, close, high, low, updown, fractal, zzid, zzupdown, zzlength) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
cursor.execute(sql, (getpair, gettf, gettime, getopen, getclose, gethigh, getlow, getcUpdown, getfractal, getzzId, getzzUpdown, getzzEndPrc))
cursor.execute(sql, ...) needs to be moved into the body of the for loop.

Chinese character doesn't support for Sqlite3 through CGI script

inserting Chinese character into Sqlite3 through Cgi script is not working for me. I can insert and select Chinese character from same database using Query browser tool but when I use python script for this, it's show error. This is the query i have used for create database
CREATE TABLE registrations (
m_username VARCHAR PRIMARY KEY
COLLATE 'BINARY',
m_identity VARCHAR,
m_updatetime DATETIME
);
and then this is the cgi script i have used for update and select values form the database
#! /Python26/python
dbFile = 'D:/sqlite/registrations'
import cgi
import sqlite3
import xml.sax.saxutils
query = cgi.parse()
db = sqlite3.connect(dbFile)
user = query.get('username', [None])[0]
identity = query.get('identity', [None])[0]
friends = query.get('friends', [])
print 'Content-type: text/plain\n\n<?xml version="1.0" encoding="utf-8"?>\n'
print "<result>"
if user:
try:
c = db.cursor()
c.execute("insert or replace into registrations values (?, ?, datetime('now'))", (user, identity))
print "\t<update>true</update>"
except:
print '\t<update>false</update>'
for f in friends:
print "\t<friend>\n\t\t<user>%s</user>" % (xml.sax.saxutils.escape(f), )
c = db.cursor()
c.execute("select m_username, m_identity from registrations where m_username = ? and m_updatetime > datetime('now', '-1 hour')", (f, ))
for result in c.fetchall():
eachIdent = result[1]
if not eachIdent:
eachIdent = ""
print "\t\t<identity>%s</identity>" % (xml.sax.saxutils.escape(eachIdent), )
if f != result[0]:
print "\t\t<registered>%s</registered>" % (xml.sax.saxutils.escape(result[0]), )
print "\t</friend>"
db.commit()
print "</result>"
I think, i need to set CHARSET as UTF-8 something, but I don't know how to do it. i was googled, but couldn't find good way to solve this issue. kindly some one help me please.
I have done this through the client side. I just used EncodeBase64 and encoded the chinese data and send to the db. I think, this one is not straight way. but I couldn't find any other way.

PyODBC - cursor record value rounding

I am working on a Python script (Python version 2.5.1 on Windows XP) that involves connecting to a Microsoft Access (.mdb) database to read values from a table. I'm getting some unexpected results with one record whereby the field of interest precision is getting rounded.
I know the Access table field of interest is a Double data type. But, the value that caused me to discover this in the table is 1107901035.43948. When I read the value in the Python code and print it out, it's showing 1107901035.44.
Is there a pyODBC connection parameter or other that must be set? I couldn't find anything in the documentation
Here's what my code looks like (the intention is to resolve unneeded records by identifying the record that has the greatest value for my field of interest):
conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' + pGDB)
conn.autocommit = True
cursor = conn.cursor()
tableList = []
for x in cursor.tables():
val = str(x[2])
if val[0:3] <> "MSy":
if val[0:3] <> "GDB":
if val[-5:] <> "Index":
tableList.append(val)
for x in tableList:
try:
SQL = "SELECT * FROM %s" % (x)
cursor.execute(SQL)
rows = cursor.fetchall()
counter = 0
for row in rows:
counter +=1
if counter > 1:
print "Site %s is a multipart basin" % (x)
SQL = "SELECT MAX(Shape_Area) AS AREA FROM %s" % (x)
cursor.execute(SQL)
row = cursor.fetchone()
val = row.AREA
print str(val)
SQL = "DELETE * FROM %s WHERE Shape_Area < %s" % (x, val)
cursor.execute(SQL)
thanks,
Tom
Django uses the Jinja template, so you can use its round filer. It works as follows:
template.html
<p>{{ VALUE| round(2, 'floor') }}</p>
Check out Jinja's documentation on topic
The SQL round function can also do this job:
SQL = "SELECT ROUND(MAX(Shape_Area), 2) AS AREA FROM %s" % (x)

Categories