python 與 MySQL數(shù)據(jù)庫
入門
上代碼
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import MySQLdb
import random
conn = MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='zeratel30000',
db='lhf_db_test_1',
)
cur = conn.cursor()
# 創(chuàng)建數(shù)據(jù)表
# cur.execute(
#? ? "CREATE TABLE colleague(id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,name VARCHAR(20),class VARCHAR(30),age VARCHAR(10))CHARACTER SET utf8 COLLATE utf8_general_ci")
# 插入一條數(shù)據(jù)
# cur.execute("INSERT INTO colleague VALUES('2','Tom','3 year 2 class','9')")
# a = 1000
# while a > 0:
#? ? a -= 1
#? ? insert = "INSERT INTO colleague VALUES(null,'%s','%s','%s')" % (
#? ? ? ? ? random.choice(['qwe', 'asd', 'zxc', 'aqz', 'wsx', 'edc']),
#? ? ? ? random.choice(['apple', 'pear', 'peach', 'orange', 'lemon']), random.randint(1, 100))
#? ? cur.execute(insert)
# 修改查詢條件的數(shù)據(jù)
# executeStr = cur.execute("UPDATE colleague SET class='3 year 1 class' WHERE name = 'Tom'")
executeStr = cur.execute("SELECT * from colleague WHERE name='asd'")
print(executeStr)
i = 0
while i < executeStr:
i += 1
print(cur.fetchone())
# # 刪除查詢條件的數(shù)據(jù)
# cur.execute("DELETE FROM colleague WHERE age='9'")
cur.close()
conn.commit()
conn.close()