python mysql基本操作

时间:2023-03-09 02:32:55
python mysql基本操作

1.创建数据库、表添加数据。

# -*- coding: utf-8 -*-
import MySQLdb.cursors
conn =MySQLdb.connect('127.0.0.1','root','',charset = 'utf8')
cur = conn.cursor() ##得到游标 cur.execute('create database if not exists python')##创建数据库
conn.select_db('python')
cur.execute('create table if not exists test(id int,info varchar(20))')##创建表 value=[1,'hi rollen']
cur.execute('insert into test values(%s,%s)',value) #添加一条数据
values=[]
for i in range(2,20):
values.append((i,'hi rollen'+str(i)))
cur.executemany('insert into test values(%s,%s)', values) ##添加多条数据 conn.commit() ##提交事务
cur.close()
conn.close()

2.修改、删除数据库操作

# -*- coding: utf-8 -*-

import MySQLdb.cursors
conn =MySQLdb.connect('127.0.0.1','root','',charset = 'utf8')
conn.select_db('python')
cur = conn.cursor() ##得到游标 cur.execute('update test set info="I am rollen" where id=3') ##修改数据
cur.execute('delete from test where id = 1') ##删除数据 conn.commit() ##提交事务
cur.close()
conn.close()

3.查询数据库

# -*- coding: utf-8 -*-
import MySQLdb.cursors
conn =MySQLdb.connect('127.0.0.1','root','',charset = 'utf8')
cur = conn.cursor() ##得到游标 conn.select_db('python') ##选择数据库
cur.execute('select * from test')
results = cur.fetchall() ##获得所有查询结果
for row in results:
rid = row[0]
info = row[1]
print "id=%s,info=%s" % (rid, info)
cur.close()
conn.close()
# -*- coding: utf-8 -*-