python + MySql 基本操做

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()
相关文章
相关标签/搜索