Python连接mysql

如下:

导入pymysql包就可以,

 1 import pymysql      #python3使用这个包连接mysql
 2 
 3 db = pymysql.connect('localhost','root','123456','testmysql')   #连接数据库地址、账户、密码、database
 4 
 5 cursor = db.cursor()    #cursor方法得到操作对象
 6 
 7 cursor.execute('select version()')  #执行SQL语句
 8 
 9 sql = 'select * from employee'
10 
11 cursor.execute(sql)
12 sql1 = 'insert into employee (id,name,salary,departmentid) values (8,"s8",20043,2)'      #values后面的非数字的值必须要用“ ”双引号
13 
14 sql2 = 'create table python_connect(id int primary key auto_increment,name varchar(11))'
15 sql3 = 'insert into python_connect (id,name)values (1,"yx")'    #为什么insert无效?
16 
17 sql4 = 'update python_connect set name = "xx" where id = 1'
18 
19 combine = (sql3,sql4)
20 
21 sql5 = 'delete from python_connect where id = 1'
22 cursor.execute(sql2)
23 
24 # 使用excutemany()执行多条语句
25 tmp = "insert into exch_no_rand_auto(stkcode) values(%s);"   #SQL模板字符串
26 l_tupple = [(i,) for i in range(100)]   #生成数据参数,list里嵌套tuple
27 cursor.executemany(tmp,l_tupple)
28 
29 
30 for i in combine:       #excutemany()方法可以执行多条语句,但是必须每条语句的形式一致,不一致的就用for吧
31     cursor.execute(i)
32 
33 db.commit()     #insert、update、delete语句需要commit()提交才能执行,但是select不需要,因为增删改都会对表进行改变,查不会
34 
35 
36 data = cursor.fetchone()    #fechone方法返回一条记录
37 data = cursor.fetchall()    #fetchall 返回所有记录
38 data = cursor.fetchmany(2)  #fetchmany 返回指定条记录
39 
40 print(data)
41 print(type(data))       #返回的是tuple元组类型数据
42 db.close()
原文地址:https://www.cnblogs.com/x991788x/p/13581688.html