Python操作mysql

#encoding=utf-8

#author [email protected]

importMySQLdb

#mysqlsql查询

defqueryfrommysql(table,sql):

conn=MySQLdb.connect(

host='localhost',

port=3306,

user='root',

passwd='1',

db=table,

charset='utf8'

)

cur=conn.cursor()

cur.execute(sql)

data=cur.fetchall()

returndata

cur.close()

conn.close()

#增改操作mysql

defcommittomysql(dbname,sql,values):

conn = MySQLdb.connect(

host='localhost',

port=3306,

user='root',

passwd='1',

db=dbname,

charset='utf8'

)

cur = conn.cursor()

cur.execute(sql,values)

conn.commit()

cur.close()

conn.close()

# 删除表数据

deftruncattable(dbname,sql):

conn = MySQLdb.connect(

host='localhost',

port=3306,

user='root',

passwd='1',

db=dbname,

charset='utf8'

)

cur = conn.cursor()

cur.execute(sql)

conn.commit()

cur.close()

conn.close()

#dbname="test"

#sql="insert into employee values(%s,%s,%s)"

#values=('15fds','2','3')

#committomysql(dbname,sql,values)

你可能感兴趣的:(Python操作mysql)