import pymysql class Mysql(object): def __init__(self): try: # 打開數據庫連接 #連接數據庫所需的值,可以在__init__()中傳入 self.conn = pymysql.connect( host = 'localhost', port = 3306, user = "root", passwd = 'root', db = "test", charset = 'utf8' ) except Exception as e: print(e) else: print("connect successfully") # 使用 cursor() 方法創建一個游標對象 cursor self.cur = self.conn.cursor() def create_table(self): try: # 使用 execute() 方法執行 SQL,如果表存在則刪除 self.cur.execute("DROP TABLE IF EXISTS EMPLOYEE") # 使用預處理語句創建表 sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )""" #執行sql語句 self.cur.execute(sql) print("create table success") except Exception as e: print("create table error\n" + e) def add(self): #數據庫插入語句 sql = """insert into EMPLOYEE(First_Name, Last_Name,Age,Sex,Income) values('Mac','Mohan',20,'F',2000);""" try: self.cur.execute(sql) # 提交到數據庫執行 self.conn.commit() except Exception as e: print(e) # 發生錯誤時回滾 self.conn.rollback() print("fail to add new data") else: print("insert data seccess!") # Python查詢Mysql使用 # fetchone()方法獲取單條數據, 使用fetchall()方法獲取多條數據。 # fetchone(): 該方法獲取下一個查詢結果集。結果集是一個對象 # fetchall(): 接收全部的返回結果行. # rowcount: 這是一個只讀屬性,並返回執行execute() # 方法后影響的行數。 def show(self): sql = "select * from employee" try : self.cur.execute(sql) #fetchall()返回的結果是list,list里面再嵌套list res = self.cur.fetchall() for row in res: fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4] # 打印結果 print("\n fname =%s,lname =%s,age = %d, sex=%s,income=%d \n " % (fname, lname, age, sex, income)) except Exception as e: print(e + "select data fail") else: print("select data success") #更新數據庫 def upodate(self): sql = "update employee set age = age + 1 where sex ='%c'" %("m") try: self.cur.execute(sql) self.conn.commit() except Exception as e: print(e) else: print("update data success") #刪除數據庫中數據 def rem(self): sql = 'delete from employee where sex = "M"' try: self.cur.execute(sql) self.conn.commit() except Exception as e: print(e) else: print("delete data success") #關閉數據庫連接 def close(self): self.cur.close() self.conn.close() print("close database success") if __name__ == "__main__": mysql = Mysql() mysql.create_table() mysql.add() mysql.show() mysql.upodate() mysql.rem() mysql.close()
可能會遇到的異常:
1.(1054, "Unknown column 'FirstName' in 'field list'") 在insert數據的時候遇到的,是因為字段沒有創建
2.1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near '' at line 1" 可能是格式有問題
3.還有一些請參考http://www.runoob.com/python3/python3-mysql.html
