python连接mysql数据库

213 阅读1分钟

import MySQLdb
conn = MySQLdb.connect(host=”localhost”,user=”root”,passwd=”“,db=”mytest”,charset=”utf8”)
cursor = conn.cursor()
sql=”select * from xxx where xx=%s” :设置要上传的sql语句
key=”填空”
param = (key) :设置param,key是变量,param为sql语句中的%s
cursor.execute(sql,param) :上传sql语句和param
conn.commit() :执行命令
n = cursor.fetchall() :n来获取所有的返回内容 是一个二维数组,n[i][j]
for data in cursor.fetchall()
print ‘%s’%data :显示结果
fetchone() :得到结果集的下一行
fetchmany() :得到结果的下几行
conn.close() :关闭连接
conn.rollback() :回滚,取消当前事物
crant all on 数据库名字.* to users :把权限给某个用户,加S是全体用户
use test :选择要使用的数据库
drop database 数据库名字 :删除数据库
create table 表名 (login varchar(8),uid int ,prid int) :创建表
drop table 表名 :删除表
insert into 表名 values(值1,值2,值3…) :插入行
update 表名 set 字段1=xxx where 字段2=xxx :更新表