Page 127 - python
P. 127

101
































                                       ภาพประกอบที่ 9.5 การสรางตารางวิทยานิพนธ thesis


                   9.10 การนําขอมูลวิทยานิพนธใสเขาไปในตาราง thesis

                   ตัวอยางที่ 9.6 การนําขอมูลวิทยานิพนธและใสในตาราง thesis
                    import urllib, urllib.request

                    url = "http://dsdi.msu.ac.th/programming/thailis-10000.txt"
                    s = urllib.request.urlopen(url).read().decode('utf-8', 'ignore').split("\n")
                    import mysql.connector as MySQL
                    config = {'user': "i_user", 'password': "123456", 'host': "202.28.34.204",

                    'database': "i_1202201", 'raise_on_warnings': True}
                    cnx = MySQL.connect(**config)
                    cursor = cnx.cursor()
                    for i in s:

                        sql = "INSERT INTO thesis (title) VALUES(\"%s\")"%i
                        cursor.execute(sql)
                        cnx.commit()

                    cnx.close()
                                             
                                   ี่
                           ตัวอยางท 9.6 การอานไฟล thailis-10000.txt จากเว็บ dsdi.msu.ac.th จากนั้นทําการสกัด
                   รายชื่อวิทยานิพนธดวยคําสั่ง split("\n") ซึ่งเปนการแยกดวยเครื่องหมายขึ้นตนบรรทัดใหม หลังจากที่
                   เชื่อมตอเขากับ Mysql Server ไดแลวจะสรางคําสั่ง SQL ดวยขอความ "INSERT INTO thesis (title)

                   VALUES (\"%s\")"%i เมื่อตัวแปร i คือ รายชื่อวิทยานิพนธในแตละเรื่อง หลังจากนั้นทําการ execute()
                                                                         ่
                                                                   
                                                                                     ่
                                                                                     ั
                                                                         ื
                                                                                  ํ
                                        ื
                                        ่
                   และทําการ commit() เมอดาเนินการเสรจสินแลวทําการปดการสอสารดวยคาสง close()
                                           ํ
                                                           
                                                        ้
                                                     ็
   122   123   124   125   126   127   128   129   130   131   132