I am using pypyodbc to insert data into a database and when I use the cursor.execute() command I try to put the sql string and the parameters, but I get the following error:
SELECT uid FROM HP_DATA WHERE( hpName = ? AND processID = ? AND ipAddress = ? AND port = ? AND usernameTried = ? AND passwordTried = ? AND fileID = ?);
INSERT INTO HP_DATA_LOGIN_DETAIL(uid, attackDate, gmtOffset) VALUES(?, CONVERT(DATETIME, ?, 126), ?);
2016-04-19T05:40:58.000
('22007', '[22007] [Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when converting date and/or time from character string.')
This is my code:
# Inserting the info of the file that is read into HP_DATA_LOG
# This is supposed to allow us to check in the future, what files are read/unread
print("Inserting File data into HP_DATA_LOG...")
log_file_date_read = datetime.datetime.today()
log_file_date_added = datetime.datetime.fromtimestamp(os.path.getctime(path)).strftime("%Y-%m-%d %H:%M:%S.%f")
file_size = os.path.getsize(path)
#log_sql = "INSERT INTO HP_DATA_LOG(dateRead, dateAdded, fileName, fileSize) VALUES("
#log_sql += "'" + str(log_file_date_read) + "', "
#log_sql += "'" + str(log_file_date_added) + "', "
#log_sql += "'" + path + "', "
#log_sql += "" + str(file_size) + ");"
log_params = (log_file_date_read, log_file_date_added, file_name, file_size)
log_sql = '''INSERT INTO HP_DATA_LOG(dateRead, dateAdded, fileName, fileSize) VALUES(?, ?, ?, ?);'''
print(log_sql)
cursor.execute(log_sql, log_params)
# Getting the auto-generated fileID from the table
print("Getting fileID...")
#get_fileID_sql = "SELECT fileID FROM HP_DATA_LOG WHERE "
#get_fileID_sql += "(dateRead = '" + str(log_file_date_read) + "'"
#get_fileID_sql += " AND dateAdded = '" + str(log_file_date_added) + "'"
#get_fileID_sql += " AND fileName = '" + path + "'"
#get_fileID_sql += " AND fileSize = '" + str(file_size) + "');"
fileID_params = (log_file_date_read, log_file_date_added, file_name, file_size)
get_fileID_sql = '''SELECT fileID FROM HP_DATA_LOG WHERE (dateRead = ? AND dateAdded = ? AND fileName = ? AND fileSize = ?);'''
print(get_fileID_sql)
cursor.execute(get_fileID_sql, fileID_params)
fileID = cursor.fetchone()
# Logging the attack by Inserting the HoneyPot data into HP_DATA
hp_name = re.findall('-\d\d:\d\d\s(.*)\ssshd', line)
pid = re.findall('\ssshd-22\[(\d+)\]', line)
ip_add = re.findall('\sIP:\s(\d+.\d+.\d+.\d+)\s', line)
port = re.findall('\s.\d+\sPass(.*)Log\s', line)
if port == "2222":
port = '2222'
else:
port = '22'
username = re.findall('\sUsername:\s(.*)\sPas', line)
password = re.findall('\sPassword:\s(.*)', line)
#sql = "INSERT INTO HP_DATA(hpName, processID, ipAddress, port, usernameTried, passwordTried, fileID) VALUES("
#sql += "'" + hp_name[0] + "', "
#sql += str(int(pid[0])) + ", "
#sql += "'" + ip_add[0] + "', "
#sql += str(port) + ", "
#sql += "'" + username[0] + "', "
#sql += "'" + password[0] + "', "
#sql += str(list(fileID)[0]) + ");"
sql_params = (hp_name[0], pid[0], ip_add[0], port, username[0], password[0], fileID[0])
sql = '''INSERT INTO HP_DATA(hpName, processID, ipAddress, port, usernameTried, passwordTried, fileID) VALUES(?, ?, ?, ?, ?, ?, ?);'''
print(sql)
cursor.execute(sql, sql_params)
#
#user_sql = r"SELECT uid FROM HP_DATA WHERE("
#user_sql += "hpName = '" + hp_name[0] + "' AND "
#user_sql += "processID = " + str(int(pid[0])) + " AND "
#user_sql += "ipAddress = '" + ip_add[0] + "' AND "
#user_sql += "port = " + str(port) + " AND "
#user_sql += r"usernameTried = '" + username[0] + "' AND "
#user_sql += r"passwordTried = '" + password[0] + "' AND "
#user_sql += "fileID = " + str(list(fileID)[0]) + ");"
user_sql_params = (hp_name[0], pid[0], ip_add[0], port, username[0], password[0], fileID[0])
user_sql = '''SELECT uid FROM HP_DATA WHERE( hpName = ? AND processID = ? AND ipAddress = ? AND port = ? AND usernameTried = ? AND passwordTried = ? AND fileID = ?);'''
print(user_sql)
cursor.execute(user_sql, user_sql_params)
uid = cursor.fetchone()
# Inserting date and time information in order to prevent duplicates
attack_date = re.findall('(\d{4}-\d\d-\d\d)T', line)
timestamp = re.findall('T(\d\d:\d\d:\d\d.*).*-.*sshd', line)
attack_datetime = attack_date[0] + "T" + timestamp[0] + ".000"
gmt_offset = re.findall('\d\d:\d\d:\d\d.*-(\d\d:\d\d)\s', line)
#hp_detail_sql = r"INSERT INTO HP_DATA_LOGIN_DETAIL(uid, attackDate, attackTime, gmtOffset) VALUES("
#hp_detail_sql += "" + str(uid[0]) + ", "
#hp_detail_sql += "'" + attackDate[0] + "', "
#hp_detail_sql += "'" + timestamp[0] + "', "
#hp_detail_sql += "'" + gmt_offset[0] + "');"
hp_detail_sql_params = (uid[0], attack_datetime[0], gmt_offset[0])
hp_detail_sql = '''INSERT INTO HP_DATA_LOGIN_DETAIL(uid, attackDate, gmtOffset) VALUES(?, ?, ?);'''
print(hp_detail_sql)
print(attack_datetime)
cursor.execute(hp_detail_sql, hp_detail_sql_params)
print("Executed insert statements")
Use datetime.strptime() to convert the attack_datetime value to a datetime object before passing the value to SQL Server.
For example, passing a datetime formatted string fails with the same error message you receive
...
# assumes connection and cursor objects initialized
create_date_str = "2016-06-16T01:23:45.67890"
sql = "select name, create_date from sys.databases where create_date = ?"
rows = cursor.execute(sql, create_date_str).fetchall()
Raises
Traceback (most recent call last): File "", line 1, in
pyodbc.DataError: ('22007', '[22007] [Microsoft][SQL Server
Native Client 11.0][SQL Server]Conversion failed when converting date
and/or time from character string. (241) (SQLExecDirectW)')
While converting the datetime string to a datetime object succeeds
...
# convert datetime string to object, specifying input format
create_date = datetime.datetime.strptime(create_date_str, '%Y-%m-%dT%H:%M:%S.%f')
rows = cursor.execute(sql, create_date).fetchall()
Related
I am writing a script that transfers data from an Access database to a MySQL database. I'm am trying to generate a query similar to below:
INSERT into customers (firstname, lastname) value ('Charlie', "D'Amelio");
However, MySQL does not like double quotes like those listed above. I wrote a clunky function to try to replace the ' in D'Amelio with a '. Here is the whole function to create the SQL statement below:
def dictionary_output(dict):
output = "INSERT into lefm_customers "
fields = "(id, "
vl = "('" + id_gen() + "', "
for key in dict.keys():
# print(dict[key])
if str(dict[key]) == 'None' or str(dict[key]) == "":
pass
elif "'" in str(dict[key]):
fields = fields + str(key) + ", "
string = ""
for character in string:
if character == "'":
string += r"\'"
else:
string += character
vl = "'" + string + "', "
else:
fields = fields + str(key) + ", "
vl = vl + "'" + str(dict[key]) + "', "
fields = fields[:-2] + ")"
vl = vl[:-2] + ");"
return "INSERT into lefm_customers " + fields + " values " + vl
Currently it is just ignoring that value altogether. Any tips on what to replace ' with or how I can improve my function? Thank you!
This fixed it:
def dictionary_output(dict):
lst = []
output = "INSERT into lefm_customers "
fields = "(id, "
vl = "('" + id_gen() + "', "
for key in dict.keys():
# print(dict[key])
if str(dict[key]) == 'None' or str(dict[key]) == "":
pass
else:
fields = fields + str(key) + ", "
vl = vl + "%s, "
lst.append(dict[key])
fields = fields[:-2] + ")"
vl = vl[:-2] + ");"
return ("INSERT into lefm_customers " + fields + " values " + vl, lst)
for name in access_dict:
if str(name) not in mysql_dict.keys():
try:
statement = dictionary_output(access_dict[name])
mysql_cursor.execute(statement[0], statement[1])
print('attempting ' + str(name))
db_connection.commit()
print("Success!")
except:
print('something went wrong')
You can just call Python's replace. Example in the terminal:
>>> s = "D'Amelio"
>>> s.replace("'", "'")
"D'Amelio"
In this case the first argument is the single quote ' and the second is the acute accent '.
My goal is to change the text color by accessing color parameters stored in a database. I am able to get the colors to work when I define them manually. However, when I try to pull them from the database the colors aren't working. I feel like I'm not converting the tuples correctly as a usable unicode, but I can't seem to wrap my head around it.
Here is my code:
#!/usr/bin/python
##### Modules to Import ######
import database
import sqlite3
##### Connect To Databases #####
conn = sqlite3.connect('project.db')
c = conn.cursor()
def workingCode():
class bcolors:
status_read = '\033[97m'
status_good = '\033[32m'
status_warning = '\033[33m'
status_bad = '\033[31m'
status_reset = '\033[0m'
print "This is how " + bcolors.status_read + "I want the " + bcolors.status_good \
+ "text to be " + bcolors.status_warning + " printed " + bcolors.status_bad \
+ " on the screen."+ bcolors.status_reset
def nonWorkingCode():
c.execute ('SELECT * FROM text_colors')
text_colors = c.fetchone()
class bcolors:
status_read, status_good, status_warning, status_bad, task_start, task_success, \
lighting_text =text_colors [:7]
print "Instead " + bcolors.status_read + "I get " + bcolors.status_good + \
"a whole " + bcolors.status_warning + " bunch of this " + bcolors.status_bad + " garbage."
workingCode()
nonWorkingCode()
Here is the finished working code I just spent 30 minutes on
let me know if you have any questions. JP:
#!/usr/bin/python
import sqlite3
from sqlite3 import Error
sqlite_file = 'project.db'
def workingCode():
class bcolors:
status_read = '\033[97m'
status_good = '\033[32m'
status_warning = '\033[33m'
status_bad = '\033[31m'
status_reset = '\033[0m'
print("This is how " + bcolors.status_read + "I want the " + bcolors.status_good \
+ "text to be " + bcolors.status_warning + " printed " + bcolors.status_bad \
+ " on the screen."+ bcolors.status_reset)
def nonWorkingCode():
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
# Create text_colors table
create_table("text_colors")
# then populate text_colors table
populate_tbl("text_colors")
c.execute('SELECT STATUS, COLOR FROM text_colors')
status_color_mappings = c.fetchall()
status_color_dictionary = dict(status_color_mappings)
print(status_color_dictionary)
class dictColors:
status_read = str(status_color_dictionary['status_read'])
status_good = str(status_color_dictionary['status_good'])
status_warning = str(status_color_dictionary['status_warning'])
status_bad = str(status_color_dictionary['status_bad'])
status_reset = str(status_color_dictionary['status_reset'])
print("Instead " + dictColors.status_read + "I get " + dictColors.status_good + "a whole " +
dictColors.status_warning + " bunch of this " + dictColors.status_bad + " garbage." +
" on the screen."+ dictColors.status_reset)
def create_table(ptbl):
""" Assemble DDL (Data Definition Language) Table Create statement and build
sqlite3 db table
Args:
string: new db table name.
Returns:
Status string, '' or 'SUCCESS'.
"""
retval = ''
sqlCmd = ''
try:
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
if ptbl == 'text_colors':
sqlCmd = 'CREATE TABLE IF NOT EXISTS ' + ptbl + ' (STATUS TEXT, COLOR TEXT)'
else:
pass
if sqlCmd != '':
c.execute(sqlCmd)
conn.commit()
conn.close()
retval = 'SUCCESS'
except Error as e:
retval = 'FAIL'
print(e)
return retval
def populate_tbl(p_fml_tbl):
"""
:param p_fml_tbl:
:return:
"""
retval = ''
try:
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
c.execute('INSERT INTO ' + p_fml_tbl + ' (STATUS, COLOR) VALUES (?, ?)', ('status_read', '\033[97m'))
c.execute('INSERT INTO ' + p_fml_tbl + ' (STATUS, COLOR) VALUES (?, ?)', ('status_good', '\033[32m'))
c.execute('INSERT INTO ' + p_fml_tbl + ' (STATUS, COLOR) VALUES (?, ?)', ('status_warning', '\033[33m'))
c.execute('INSERT INTO ' + p_fml_tbl + ' (STATUS, COLOR) VALUES (?, ?)', ('status_bad', '\033[31m'))
c.execute('INSERT INTO ' + p_fml_tbl + ' (STATUS, COLOR) VALUES (?, ?)', ('status_reset', '\033[0m'))
conn.commit()
conn.close()
retval = 'SUCCESS'
except Error as e:
print(e)
return retval
if __name__ == '__main__':
workingCode()
nonWorkingCode()
This is the following code
pythonlist = ['Name','Mno']
datalist = ["qwerty",'234']
sql = "SELECT " + ",".join(pythonlist) + " FROM data WHERE name = '"+ "','".join(datalist) + "' INTO OUTFILE filename"
print(sql)
OUTPUT:
SELECT Name,Mno FROM data WHERE Name= 'qwerty','234'
DESIRED OUTPUT:
SELECT Name,Mno FROM data WHERE Name = 'qwerty' and Mno = 234
Do note the removal of quotations marks in 'mno'.
The reason I am doing this is due because the column names, as well as values corresponding it to, will change frequently
Code :
queryparams = {'Name': 'qwerty', 'Mno': '234'}
and_clause = []
[and_clause.append(' %s = %s ') for k,v in queryparams.items()]
and_clause_str = ' and '.join(and_clause)
sql = 'SELECT %s FROM data WHERE ' + and_clause_str
params = [','.join(queryparams.keys())]
for k,v in queryparams.items():
params.append(str(k))
params.append(str(v))
print(sql)
print(params)
cursor.execute(sql, params=tuple(params))
This works if you add 10/20 more items to dictionary .
Aswell as prevents SQL-injection : Using params to pass values instead of string-concatenation .
Try this:
data = {'Name': 'qwerty' , 'Mno' : '234'}
sql = "SELECT " + ", ".join(data.keys()) + " FROM data WHERE " + str(list(data.keys())[0]) + " = '" + \
str(data[list(data.keys())[0]]) + "' and " +\
str(list(data.keys())[1]) + " = " + str(data[list(data.keys())[1]])
print(sql)
I have to connect the sql database to python so that I can add new user data via python.
I have tried the int conversion which puts me in further trouble of null types dataset.
i have tried the bracket placement. It doesn't work.
import os
import datetime
import pyodbc
import sqlite3
file_open = open("filenames.txt","r")
path = 'C:\\Users\\Timble\\Desktop\\Face_recognition\\user-id_filenames\\'
flag_loc = 1
flag_proc = 0
flag_vis = 0
file_read_lines = file_open.readlines()
for line in file_read_lines:
for character in line:
if character == "_":
details = line.split("_")
now = datetime.datetime.now()
name = line
print("name:", name) #col-3
print("type of name:", type(name))
user_id = int(details[1])
print("user_id:", details[1]) #col-2
print("type of user_id:", type(user_id))
date = details[2]
print("date on which photo is taken:", details[2]) #col-4
print("type of data:",type(details[2]))
now = now.strftime("%Y-%m-%d %H:%M:%S")
print("Current date and time: ", now) #col-6
print("type of current date:", type(now))
path2 = path + details[1]
if os.path.exists(path2):
print(path2)
else:
os.makedirs(path2)
#break
date = str(date)
print("type of date", type(date))
user_id = str(user_id)
print("type of user_id", type(user_id))
name = str(name)
print("type of name",type(name))
now = str(now)
print("type of now", type(now))
flag_loc = str(flag_loc)
print("type loc flag", type(flag_loc))
flag_proc = str(flag_proc)
print("type proc flag", type(flag_proc))
flag_vis = str(flag_vis)
print("type vis flag", type(flag_vis))
conn = pyodbc.connect(
"DRIVER={SQl Server};"
"server=DESKTOP-3ORBD3I\MSSQL;"
"database=TimbleSecuritySystem;"
"uid=sa;"
"pwd=P#ssword")
cur = conn.cursor()
sqlInsertUser = "Insert Into retraining (date, user_id, image_name,location_flagged, processing_flagged, insert_date, visible)Values( "+ date + " , " + user_id + " , " + name + " , " + flag_loc + " , " + flag_proc + " , " + now + " , " + flag_vis + " )"
print(sqlInsertUser)
cur.execute(sqlInsertUser)
conn.commit()
break
file_open.close()
The actual results tell me that print(sqlInsertUser) prints all the right values.
I am expecting the execute command to work and sql data added there.
This line is the problem:
sqlInsertUser = "Insert Into retraining (date, user_id, image_name,location_flagged, processing_flagged, insert_date, visible)Values( "+ date + " , " + user_id + " , " + name + " , " + flag_loc + " , " + flag_proc + " , " + now + " , " + flag_vis + " )"
For example if name contains some invalid characters e.g. "[" or "]", then the execute call fails because the name string is not properly enclosed. (It should be enclosed in a pair of quote)
You can use the parameter substitution support in pyodbc e.g.
sqlInsertUser = "Insert Into retraining (date, user_id,
image_name, location_flagged, processing_flagged, insert_date,
visible) Values (?,?,?,?,?,?,?)"
then run
cur.execute(sqlInsertUser, date, user_id, name, flag_loc, flag_proc, now, flag_vis)
(My sample code above is untested. You might need to fix some syntax errors)
For more details about the syntax see https://www.python.org/dev/peps/pep-0249/#paramstyle or https://github.com/mkleehammer/pyodbc/wiki/Cursor
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have two almost identical programs. One works, the other does not. The program that is not working displays the error "not enough arguments for format string". It probably has something to do with the "%" in the variable dbname, but I can't figure out why one program works and the other does not. In both programs I'm attempting to use a wildcard in a SELECT statement with LIKE.
Working program:
import subprocess
import sys
import commands
from sqlalchemy import create_engine
from sqlalchemy import Date, DateTime
from sqlalchemy import create_engine
from sqlalchemy import MetaData, Column, Table, ForeignKey
from sqlalchemy import Integer, String
from sqlalchemy.sql import select
engine = create_engine('mysql://UID:PASS#999.999.99.99:9999/access_benchmark_staging', echo=True)
dest = engine.connect()
dest.execute("truncate table TABAUTH")
def dbapull(applid, ssid, host, port, dbname):
print "dbapull " + dbname + ""
source = pyodbc.connect('Driver={IBM DB2 ODBC DRIVER};Database=' + ssid +';Hostname=' + host + ';Port=' + port + ';Protocol=TCPIP;Uid=user;Pwd=password', echo=True)
src = source.cursor()
src.execute("SELECT DISTINCT SUBSTR(CURRENT SERVER,1,7) AS SSID, SUBSTR(B.GRANTEE,1,8) AS GRANTEE, B.UPDATEAUTH AS U, B.INSERTAUTH AS I, B.DELETEAUTH AS D, A.CREATOR, B.DBNAME, B.TTNAME, B.ALTERAUTH AS C FROM " + ssid + ".SYSIBM.SYSTABLES A LEFT JOIN " + ssid + ".SYSIBM.SYSTABAUTH B ON A.CREATOR = B.TCREATOR AND A.NAME = B.TTNAME WHERE A.CREATOR IN ('PFPROD','PGPROD','PSPROD','PS','PROD') AND A.DBNAME LIKE " + dbname + " AND (B.UPDATEAUTH <> ' ' OR B.INSERTAUTH <> ' ' OR B.DELETEAUTH <> ' ') AND A.TYPE IN ('T','V') AND B.GRANTEETYPE = ' ' AND A.NAME NOT IN ('DSN_VIEWREF_TABLE','DSN_PGRANGE_TABLE','DSN_SORTKEY_TABLE','DSN_SORT_TABLE','DSN_DETCOST_TABLE','DSN_FILTER_TABLE','DSN_PTASK_TABLE','DSN_STATEMNT_TABLE','DSN_PGROUP_TABLE','DSN_STRUCT_TABLE','DSN_PREDICAT_TABLE','PLAN_TABLE') ORDER BY 2")
for row in src:
#print (row)
row[0] = str(row[0]).strip()
row[1] = str(row[1]).strip()
row[2] = str(row[2]).strip()
row[3] = str(row[3]).strip()
row[4] = str(row[4]).strip()
row[5] = str(row[5]).strip()
row[6] = str(row[6]).strip()
row[7] = str(row[7]).strip()
row[8] = str(row[8]).strip()
result = dest.execute("insert ignore into TABAUTH values ('" + applid + "','" + row[0] + "','" + row[1] + "','" + row[2] + "','" + row[3] + "','" + row[4] + "','" + row[5] + "','" + row[6] + "','" + row[7] + "','" + row[8] + "')")
dbapull("AAA", "BBB", "CCC", "DDD", "'%PMC%'")
dest.close()
Non-working program:
import subprocess
import sys
import commands
from sqlalchemy import create_engine
from sqlalchemy import Date, DateTime
from sqlalchemy import create_engine
from sqlalchemy import MetaData, Column, Table, ForeignKey
from sqlalchemy import Integer, String
from sqlalchemy.sql import select
engine = create_engine('mysql://UID:PASS#999.999.99.99:9999/access_benchmark_staging', echo=True)
dest = engine.connect()
dest.execute("truncate table DS_Users")
def userpull(appl, dbname):
print "DS User pull " + dbname + " "
source = create_engine('mysql://UID:PASS#999.999.99.99:9999/access_benchmark_staging', echo=True)
src = engine.connect()
src.execute("SELECT MF.profile_name AS profile_name, MF.groupuser_access as groupuser_access, MF.group_id as group_id, MF.user_id as user_id, MF.user_name as user_name, MF.default_group as default_group, MF.last_racinit as last_racinit, MF.password_last_changed_date as password_last_changed_date, MF.user_id_status as user_id_status, MF.creation_date as creation_date, ldap.uid as uid, ldap.company as company, ldap.emp_name as emp_name, ldap.title as title, ldap.contract_exp as contact_exp, ldap.dept_name as dept_name, ldap.emp_status as emp_status, ldap.disabled_date as disabled_date, ldap.term_date as term_date, ldap.bus_unit as bus_unit, ldap.manager_id as manager_id FROM (SELECT DST.profile_name, DST.groupuser_access, GRP.group_id, USR.user_id, USR.user_name, USR.default_group, USR.last_racinit, USR.password_last_changed_date, USR.user_id_status, USR.creation_date FROM AU_KRC_USER_REPORT USR INNER JOIN AU_KRC_GROUP_REPORT GRP ON USR.user_id = GRP.user_id INNER JOIN AU_KRC_DATASET_REPORT DST ON GRP.group_id = DST.groupuser_id WHERE (DST.profile_name LIKE " + dbname + " AND DST.profile_name NOT IN ('" + appl + ".SYSINFO.ABEND')) AND DST.groupuser_access IN ('UPDAT', 'ALTER') AND DST.groupuser_type = 'GROUP' ) MF LEFT OUTER JOIN ldap.ldap_raw ldap ON MF.user_id = ldap.kmart_mf GROUP BY MF.group_id, MF.user_id, MF.user_name, MF.default_group, MF.last_racinit, MF.password_last_changed_date, MF.user_id_status, MF.creation_date, ldap.uid, ldap.company, ldap.emp_name,ldap.title, ldap.contract_exp, ldap.dept_name, ldap.emp_status, ldap.disabled_date, ldap.term_date, ldap.bus_unit, ldap.manager_id")
for row in src:
#print (row)
row[0] = str(row[0]).strip()
row[1] = str(row[1]).strip()
row[2] = str(row[2]).strip()
row[3] = str(row[3]).strip()
row[4] = str(row[4]).strip()
row[5] = str(row[5]).strip()
row[6] = str(row[6]).strip()
row[7] = str(row[7]).strip()
row[8] = str(row[8]).strip()
row[9] = str(row[9]).strip()
row[10] = str(row[10]).strip()
row[11] = str(row[11]).strip()
row[12] = str(row[12]).strip()
row[13] = str(row[13]).strip()
row[14] = str(row[14]).strip()
row[15] = str(row[15]).strip()
row[16] = str(row[16]).strip()
row[17] = str(row[17]).strip()
row[18] = str(row[18]).strip()
row[19] = str(row[19]).strip()
row[20] = str(row[20]).strip()
result = dest.execute("insert ignore into DS_Users values ('" + appl +"','" + row[0] + "','" + row[1] + "','" + row[2] + "','" + row[3] + "','" + row[4] + "','" + row[5] + "','" + row[6] + "','" + row[7] + "','" + row[8] + "','" + row[9] + "','" + row[10] + "','" + row[11] + "','" + row[12] + "','" + row[13] + "','" + row[14] + "','" + row[15] + "','" + row[16] + "','" + row[17] + "','" + row[18] + "','" + row[19] + "','" + row[20] + "')")
userpull("PP", "'%PP.%'")
Try to put your sql in a transaction and check if the driver you are using for the DB support the "%" for queries.