Search code examples
mysqlpython-2.7mysql-pythonxlrd

SELECT within INSERT Values Error


I'm trying to insert data to the table. The data can be either from a CSV or from another table based on a value from the CSV.

Error I am getting:

unsupported format character 'R' (0x52) at index 64

Code:

def Test():
path = 'USA DIRECT.xls'
workbook = xlrd.open_workbook(path, on_demand = True)
sheet = workbook.sheet_by_index(0)
for rowx in xrange(1, sheet.nrows):
    try:
        Id = ''
        Year = datetime.now().strftime('%Y')
        Month = datetime.now().strftime('%m')
        Partner = 'USA Direct'
        PartnerType = 'Direct'
        Reseller = sheet.row_values(rowx, start_colx=12, end_colx=None)[0]
        Model = sheet.row_values(rowx, start_colx=2, end_colx=None)[0]
        InvDate = sheet.row_values(rowx, start_colx=11, end_colx=None)[0]
        CustomerNumber = ''
        Zip = sheet.row_values(rowx, start_colx=22, end_colx=None)[0]
        Quantity = sheet.row_values(rowx, start_colx=7, end_colx=None)[0]
        Total = sheet.row_values(rowx, start_colx=25, end_colx=None)[0]
        UnitPrice = sheet.row_values(rowx, start_colx=24, end_colx=None)[0]

        cursor.execute("INSERT INTO sales_olap (id, year, month, reporting_partner, reporting_partner_type, reseller_name, reseller_type, reseller_state, part_number, part_category, product_family, invoice_date, reseller_customer_number, reseller_zip_code, units, extended_cost, unit_cost) VALUES('%s', '%s', '%s','%s', '%s', '%s', (SELECT reseller_type FROM resellers WHERE reseller='%s' % Reseller), (SELECT reseller_state FROM resellers WHERE reseller='%s' % Reseller),'%s', (SELECT category FROM models WHERE model='%s' % Model), (SELECT family FROM models WHERE model='%s' % Model), '%s', '%s', '%s', '%s', '%s', '%s')" %(Id, Year, Month, Partner, PartnerType, Reseller, Model, InvDate, CustomerNumber, Zip, Quantity, Total, UnitPrice))
    except Exception, e:
        print (e)
workbook.release_resources()

Any help would be greatly appreciated.


Solution

  • This is the fust occurrence of letter R(0x52) in your query.

    SELECT reseller_type FROM resellers WHERE reseller='%s' % Reseller

    Looking at it you need to escape % with prefixing another % since it's not wrapped in quotes i.e.

    SELECT reseller_type FROM resellers WHERE reseller='%s' %% Reseller

    Applies to other inner selects as well