安装MySQL驱动
由于MySQL服务器以独立的进程运行,并通过网络对外服务,所以,需要支持
Python的MySQL驱动来连接到MySQL服务器。1
pip install pymysql
连接test数据库1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34import pymysql
conn = pymysql.connect('localhost', 'root', 'root', 'test') #链接数据库
cursor = conn.cursor()
cursor.execute('create table user (id varchar(20) primary key, name varchar(20))') # 创建user表:
cursor.execute('insert into user (id, name) values (%s, %s)', ['1', 'Michael']) #插入数据四种方式
cursor.execute('insert into user (id, name) values (%s, %s)', ('4', 'Jack'))
user_id = '2'
user_name = 'suki'
cursor.execute('insert into user values("%s", "%s")' % (user_id, user_name))
cursor.execute('insert into user (id, name) values ("%s", "%s")' % ('3', 'Adam'))
print(cursor.rowcount)
#提交事务:
conn.commit()
cursor.close()
#运行查新
cursor = conn.cursor()
cursor.execute('select * from user where id = %s', '4')
#cursor.execute('select * from user where id = "%s"' % '2')
values = cursor.fetchall()
value = cursor.fetchone()
print(values)
print(value)
#关闭Cursor和Connection:
cursor.close()
conn.close()
小结
执行INSERT等操作后要调用commit()提交事务