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()
ํ
้
็