10-pymysql的應用
阿新 • • 發佈:2019-01-04
import pymysql # user = input('請輸入使用者名稱:') # pwd = input('請輸入密碼:') # 1.建立連線 conn = pymysql.connect(host='127.0.0.1', user='root', password="", database='db8', port=3306, charset='utf8') # 2.建立遊標 cur = conn.cursor(cursor=pymysql.cursors.DictCursor) # sql = "select * from userinfo where name='%s' and pwd='%s'" %(user,pwd)# sql = "select * from userinfo where name=%s and pwd=%s" # sql = "select * from userinfo where name=%(user)s and pwd=%(pwd)s" # 插入資料 # sql = 'insert into userinfo(name,pwd) values(%s,%s)' # print(sql) # 3執行sql語句 # r = cur.execute(sql,[user,pwd]) # r = cur.execute(sql,(user,pwd)) # r = cur.execute(sql,{"user":user,"pwd":pwd})#插入多條資料 # r = cur.executemany(sql, [('李四', '110'), ('王五', '119')]) # print(r) sql = 'select * from userinfo' cur.execute(sql) # row = cur.fetchone() # print(row) # row = cur.fetchone() # print(row) # row = cur.fetchone() # print(row) # row = cur.fetchone() # print(row) # row = cur.fetchone() # print(row)# rows = cur.fetchmany() # # print(rows) rows = cur.fetchall() print(rows) # 增 刪 改 一定要提交 conn.commit() # 關閉遊標 關閉連線物件 cur.close() conn.close() # if r: # print('查詢成功') # else: # print('查詢失敗')