python + mysql數據庫的連接python
一、安裝mysqlmysql
pip install PySQLdb
二、鏈接數據庫sql
# -*- coding: UTF-8 -*- import MySQLdb # 打開數據庫鏈接 db = MySQLdb.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='gz_information', charset='utf8') # 使用cursor()方法獲取操做遊標 cursor = db.cursor() # 使用execute方法執行SQL語句 cursor.execute("SELECT * FROM user") data = cursor.fetchall() # # 使用 fetchone() 方法獲取一條數據 # data = cursor.fetchone() print data # 關閉數據庫鏈接 db.close()
三、插入數據數據庫
insert = "insert into user(username, password) values('aaaa','aaaa')" print insert cursor.execute(insert) db.commit() #將插入的數據提交至數據庫執行
四、刪除數據fetch
de = "delete from user where username = 'aaaa'" print de cursor.execute(de) db.commit()
五、更新數據spa
update = "update user set password='123123' where username = '1'" print update cursor.execute(update) db.commit()