#__author: hasee #date: 2018/1/17 # python程序连接数据库,需要提前准备好第三方库(不同类型的数据库第三方库不同) # 利用python开发环境中自带的pip工具完成第三方库的安装 pip install pymysql # 数据库连接过程 # 1、准备第三方库 # 2、在程序中import模块 # 3、利用pymysql模块中的connect建立与数据库服务器的连接 # 4、建立连接后返回连接对象 # 4.1 close() # 4.2 commit() # 4.3 rollback() # 4.4 cursor() # 5、利用连接对象调用cursor()创建一个游标对象,完成对数据库的操作 # 5.1 execute() # 5.2 executemany() # 5.3 callproc() # 5.4 fetchone() 在执行了SELECT命令后 # 5.5 fetchall() 在执行了SELECT命令后 # 5.6 fetchmany()在执行了SELECT命令后 # 5.7 close() # 6、如果对数据库做了增、删、改操作,需要commit() # 7、释放游标、释放连接 import pymysql # connect()函数返回一个数据库连接对象,主要负责管理程序与数据库的连接 # grant all on *.* to 'root'@'%' identified by '123456' # flush previleges conn = pymysql.connect(host='192.168.8.30', port=3306, user='root', password='123456', db='test', charset='utf8') cur = conn.cursor() # 创建游标对象,主要负责完成数据库中数据的具体操作 cur.execute('select * from student') # result1=cur.fetchone() #readline()相似 # print(result1) #fetchone()获取结果集中的一行记录,并把这一行记录中的多个属性值放到元组中管理 # result2=cur.fetchall() #readlines相似 # print(result2) #fetchall()获取多行记录,每行记录包含多个属性值 放到元组(嵌套)中管理 外层元组管理多行记录,内层元组管理每行记录的多个属性值 # result3=cur.fetchmany(2) #同fetchall()类似,需要指定获取的记录数量 # print(result3) # result=cur.execute('insert into student values(1,"zhangsan")) #execute()返回值为SQL命令执行后,数据库中收到影响的记录数量 # cur.execute('insert into student values(%d,%r)'%(i,'zhangsan'+str(i))) # cur.execute('insert into student values(%d,"zhangsan")'%10) #字符串格式化 # cur.execute('insert into student values(%s,"zhangsan")',10) #第二个参数 # cur.execute('insert into student values(%s,%s)',[10,'zhangsan']) # cur.execute('insert into student values(%s,%s),(%s,%s)',[10,'zhangsan',20,'lisi']) # cur.executemany('insert into student values(%s,"zhangsan")',[1,2,3,4,5]) #executemany() 将同样一条SQL命令重复执行多次,相当于execute()+for循环 # cur.executemany('insert into student values(%s,%s)',[[1,'zhangsan'],[2,'lisi'],[3,'wangwu']]) ''' for i in range(1,6): cur.execute('insert into student values(%s,"zhangsan")',i) ''' # cur.callproc('p1') #完成数据库中已经定义好的存储过程的调用(存储过程不能有输出参数) cur.close() conn.commit() # 提交事务,程序中对数据库做的操作默认都是属于同一个事务的 # conn.rollback() #撤销事务 conn.close()