473,406 Members | 2,467 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Can I get help importing an excel document into mysql using python please?

Hello,
This is my first time posting and just my second day using python on mysql, so please be patient with me. I should also say, I am using a linux machine. Using python I was able to make a database and a table. However, I am having difficulty getting the values from an excel and putting them into the table. The Excel document has just three columns, which are:
MATCH - this is just a four digit number
DATE - this is just a date in the 2009-06-29 format
POS - this is either just the phrase 'LONG' or 'SHORT'

However, after I do this and try to view the data, the MATCH values come out perfectly fine. The date values come out 0000-00-00 for all the dates, so that is not correct. and for the POS, I get this error:
mysql_exceptions.OperationalError: (1054, “Unkown column 'SHORT' in 'field list'”)

I have tried changing the variable types from VARCHAR to TEXT or DATE, but that didn't seem to work. Really any suggestions would be greatly appreciated.

The Code I am using is:
Expand|Select|Wrap|Line Numbers
  1. from xlrd import open_workbook, cellname
  2. import MySQLdb as mysql
  3. db=mysql.connect(db_info)
  4. c=db.cursor()
  5. c.execute('CREATE DATABASE actual_data')
  6.  
  7. db=mysql.connect(db_info)
  8. c=db.cursor()
  9. c.execute('CREATE TABLE actual_data_table (MATCH_ID VARCHAR(35) NOT NULL,DATETIME VARCHAR(35) NOT NULL,POS_TYPE VARCHAR(35) NOT NULL)')
  10.  
  11. file_to_import='actualdata.xls'
  12. column_count=5
  13. book=open_workbook(file_to_import)
  14. sheet=book.sheet_by_index(0)
  15. conn=mysql.connect(db_info)
  16. cursor=conn.cursor()
  17.  
  18. for row_index in range(sheet.nrows):
  19.  
  20.     row_num=row_index
  21.     MATCH_ID=sheet.cell(row_index,0).value
  22.     DATETIME=sheet.cell(row_index,1).value
  23.     POS_TYPE=sheet.cell(row_index,2).value
  24.  
  25.     cursor.execute('INSERT INTO actual_data_table(MATCH_ID, DATETIME, POS_TYPE) VALUES (%s, %s, %s)'%(MATCH_ID, DATETIME, POS_TYPE))
  26.  
  27.     (MATCH_ID,DATETIME,POS_TYPE)
  28.  
  29.  
  30. cursor.close()
  31. conn.commit()
  32. conn.close()
Aug 18 '10 #1

✓ answered by bvdet

No problem:
Expand|Select|Wrap|Line Numbers
  1. >>> result
  2. (('15.64',), ('-5.2',), ('24.25',), ('22.18',), ('14.52',), ('21.8',), ('21.2804',), ('-0.13',), ('15.48',), ('2.2',), ('-6.81',))
  3. >>> for item in result:
  4. ...     print float(item[0])
  5. ...     
  6. 15.64
  7. -5.2
  8. 24.25
  9. 22.18
  10. 14.52
  11. 21.8
  12. 21.2804
  13. -0.13
  14. 15.48
  15. 2.2
  16. -6.81
  17. >>> sum([float(item[0]) for item in result])/len(result)
  18. 11.382763636363636
  19. >>> 

6 7342
dwblas
626 Expert 512MB
You first want to make sure that the data types are the same, so read the first 10 recs or so and print out the fields, and type(DATE), etc. and make sure they are strings. Second, I think the format for a MySQL insert is (note that you should be using "c" according to your code, and not "cursor")
c.execute('insert into actual_data_table values ("%s","%s","%s")' % (MATCH_ID, DATETIME, POS_TYPE))

Another option just in case because I use another SQL and have both of these examples in the MySQL notes
c.execute(u'''INSERT INTO actual_data_table VALUES (%s, %s, %s)''', MATCH_ID, DATETIME, POS_TYPE)
This avoids SQL injection AFAIK

Finally, you have duplicate code. You can delete the first occurrence of
Expand|Select|Wrap|Line Numbers
  1. db=mysql.connect(db_info)
  2. c=db.cursor()
  3. c.execute('CREATE DATABASE actual_data')
Aug 18 '10 #2
bvdet
2,851 Expert Mod 2GB
Excel stores dates as integers. When you read an actual date from an Excel file with xlrd, the date comes in as a float. It represents the number of days since Jan 1, 1900 (Windows). To input the proper information into your database, you can first convert the float into a date. This works for me on my system:
Expand|Select|Wrap|Line Numbers
  1. import time
  2. import datetime
  3.  
  4. wb = xlrd.open_workbook('data.xls')
  5. sheet1 = wb.sheet_by_index(0)
  6.  
  7. rowList = sheet1.row_values(1)
  8. dateStr = datetime.datetime(*time.strptime("Dec 30 1899", "%b %d %Y")[:6]) + \
  9. datetime.timedelta(days=int(rowList[1]))
I used "Dec 30, 1899" instead of "Jan 1, 1900" because of a 2 day difference between expected results and actual results. It's possible Excel and Python calculate leap years differently.
Aug 18 '10 #3
Hello,
I am attempting to import an excel document into a mysql database using python. The excel document has three columns of data: MATCH_ID, DATETIME, and POS_TYPE. Using the code I'll show at the end, I have successfully imported the excel document except for one problem. The column DATETIME has values in the format of 'yyyy-mm-dd'. Yet when I try the importing, all the values just come out as '0000-00-00'. When I tried importing this as a varchar file, all of the numbers that came out were just a large five-digit number. I;m thinking this may have something to do with the formating of the cells in excel. The other two values which are just a number string and a short word import perfectly. I have tried changing the variable type, but that was not helpful. Clearly form my code you can see I quite new at this. Your help will be very much appreciated.

Expand|Select|Wrap|Line Numbers
  1. from xlrd import open_workbook, cellname
  2. import MySQLdb as mysql
  3. db=mysql.connect(db_info)
  4. c=db.cursor()
  5. c.execute('CREATE DATABASE actual_data')
  6.  
  7. db=mysql.connect(db_info)
  8. c=db.cursor()
  9. c.execute('CREATE TABLE actual_data_table (MATCH_ID VARCHAR(35) NOT NULL,DATETIME DATE NOT NULL,POS_TYPE VARCHAR(35) NOT NULL, TICKER VARCHAR(35) NOT NULL, EXIT_TYPE TEXT NOT NULL)')
  10.  
  11. file_to_import='actualdata.xls'
  12. column_count=5
  13. book=open_workbook(file_to_import)
  14. sheet=book.sheet_by_index(0)
  15. db=mysql.connect(db_info)
  16. c=db.cursor()
  17.  
  18. for row_index in range(sheet.nrows):
  19.  
  20.     row_num=row_index
  21.     MATCH_ID=sheet.cell(row_index,0).value
  22.     DATETIME=sheet.cell(row_index,1).value
  23.     POS_TYPE=sheet.cell(row_index,2).value
  24.     c.execute('insert into actual_data_table values ("%s","%s","%s")' % (MATCH_ID, DATETIME, POS_TYPE))
  25.     (MATCH_ID,DATETIME,POS_TYPE)
  26.  
  27. cursor.close()
  28. conn.commit()
  29. conn.close()  
  30.  
Aug 20 '10 #4
bvdet
2,851 Expert Mod 2GB
Ron,

Please read my reply to your thread here.

To summarize, Excel stores dates as a number and formats the number for display. The number represents the number of days since Jan 1, 1900 (Windows). You can use that number to calculate the date.

bvdet
Aug 20 '10 #5
Sorry, I did not keep scrolling down to see the second part of your message. However, that was a LOT of help. THANK YOU!!

However, I have another question that should be much quicker. Using the following code I selected 11 numbers.
Expand|Select|Wrap|Line Numbers
  1. c.execute('SELECT REF_PNL FROM actual_data_table WHERE REF_ENTRY_TIME>"2010-06-29 09:45:00" and REF_ENTRY_TIME<"2010-06-29 10:00:00"')
  2. result1=c.fetchall()
  3.  
when I try to output these results, they come out like this:
>>>result1
(('15.64',), ('-5.2',), ('24.25',), ('22.18',), ('14.52',), ('21.8',), ('21.2804',), ('-0.13',), ('15.48',), ('2.2',), ('-6.81',))
This is fine, however, I can't seem to do any computations with these numbers. I'm trying to take the average of these numbers using numpy. But then I get this error:
TypeError: cannot perform reduce with flexible type

The result looks like a tuple within a tuple or something. So is there anyway to break the results down into regular computable numbers?
Aug 20 '10 #6
bvdet
2,851 Expert Mod 2GB
No problem:
Expand|Select|Wrap|Line Numbers
  1. >>> result
  2. (('15.64',), ('-5.2',), ('24.25',), ('22.18',), ('14.52',), ('21.8',), ('21.2804',), ('-0.13',), ('15.48',), ('2.2',), ('-6.81',))
  3. >>> for item in result:
  4. ...     print float(item[0])
  5. ...     
  6. 15.64
  7. -5.2
  8. 24.25
  9. 22.18
  10. 14.52
  11. 21.8
  12. 21.2804
  13. -0.13
  14. 15.48
  15. 2.2
  16. -6.81
  17. >>> sum([float(item[0]) for item in result])/len(result)
  18. 11.382763636363636
  19. >>> 
Aug 20 '10 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Little PussyCat | last post by:
Hello, I nee to write something that will transfer excel data into an SQL Server table. I have for another database application I wrote have it importing Excel spreadsheet data using cell by...
9
by: Paul | last post by:
Hi all Arggghhh........... The problem.....I want the user to be able to create an excel document and name particular cells in the document where they want the data to be placed and then save...
0
by: ramaraog80 | last post by:
Hi, Is it possible to import data from Excel Sheets to MySql. If possible please reply me with the detail Code ASAP.
2
by: WODJ | last post by:
Folks, I hope someone out there can please help me, not much hair left with this one. I'm importing excel data into a SQL server database using an Oledb connection in C#. The problemm is that...
1
by: chirag thakor | last post by:
how i can import data from Excel to MySql using php.
1
by: Girish | last post by:
Hi, I want to embed a txt document into an excel using python. Here is my code, but i get an error message =================================================== Traceback (most recent call...
1
by: dsudhakara | last post by:
please help me immediatly How we wil convert from ms-Excel sheet to MySQL database using PHP
4
by: chazzy69 | last post by:
I trying to import a excel table into a mysql database table. First thing i did was make colums up according to the colum names in the excel table, then i exported the excel document as a .csv file...
1
by: Krishna | last post by:
How do I access individual fields in csv using python? Please let me know ASAP as its real urgent for me. Thanks for your help Krishna
15
numberwhun
by: numberwhun | last post by:
Ok, let me preface this thread by saying that I cannot provide a real sample of the data that I am working with. The reason is, because it contains a lot of private, confidential information (for...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.