1.ทำการ import library psycopg2 เพื่อที่จะทำการเชื่อมต่อกับ database
โค้ด: เลือกทั้งหมด
import psycopg2 as p
โค้ด: เลือกทั้งหมด
con = p.connect(
host='localhost',
database='ben01',
user='postgres',
password='postgres'
)
โค้ด: เลือกทั้งหมด
def sum_ver():
cur = con.cursor()
cur.execute("SELECT latest_version FROM ir_module_module where state = 'installed'")
total = cur.fetchall()
โค้ด: เลือกทั้งหมด
num1 = 0
num2 = 0
num3 = 0
num4 = 0
num5 = 0
ผลลัพท์ 5. ค่าที่ได้จะเป็น ประเภท list ซึ่งถ้าเราต้องการจะนำเลขภายในมาใช้เราจะต้องทำการดึง ตัวเลขภายในออกมาให้กลายเป็น string ก่อน โดยวิธีการคือเราจะใช้ for loop ในการดึงค่า
โค้ด: เลือกทั้งหมด
for row in total:
for i in row:
โค้ด: เลือกทั้งหมด
sp = i.split('.')
โค้ด: เลือกทั้งหมด
sp.append('0')
โค้ด: เลือกทั้งหมด
num1 += int(sp[0])
num2 += int(sp[1])
num3 += int(sp[2])
num4 += int(sp[3])
num5 += int(sp[4])
resu = "Summery Version = {}.{}.{}.{}.{}".format(num1, num2, num3, num4, num5)
print(resu)
ผลลัพธ์ที่ได้ fullcode
โค้ด: เลือกทั้งหมด
# -*- coding:utf-8 -*
import psycopg2 as p
con = p.connect(
host='localhost',
database='ben01',
user='postgres',
password='postgres'
)
def sum_ver():
cur = con.cursor()
cur.execute("SELECT latest_version FROM ir_module_module where state = 'installed'")
total = cur.fetchall()
num1 = 0
num2 = 0
num3 = 0
num4 = 0
num5 = 0
for row in total:
for i in row:
sp = i.split('.')
sp.append('0')
num1 += int(sp[0])
num2 += int(sp[1])
num3 += int(sp[2])
num4 += int(sp[3])
num5 += int(sp[4])
resu = "Summery Version = {}.{}.{}.{}.{}".format(num1, num2, num3, num4, num5)
print(resu)
if __name__ == '__main__':
sum_ver()
viewtopic.php?f=16&t=64136
https://www.w3schools.com/python/ref_string_split.asp
https://www.pythonforbeginners.com/dictionary/python-split