如下:
导入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无效?因为没有commit()提交执行 16 17 sql4 = ‘update python_connect set name = "xx" where id = 1‘ 18 19 sql5 = ‘delete from python_connect where id = 1‘ 20 # cursor.execute(sql2) 21 cursor.execute(sql5) 22 db.commit() #insert、update、delete语句需要commit()提交才能执行,但是select不需要,因为增删改都会对表进行改变,查不会 23 24 25 data = cursor.fetchone() #fechone方法返回一条记录 26 data = cursor.fetchall() #fetchall 返回所有记录 27 data = cursor.fetchmany(2) #fetchmany 返回指定条记录 28 29 print(data) 30 print(type(data)) #返回的是tuple元组类型数据 31 db.close()
原文:https://www.cnblogs.com/x991788x/p/13581688.html