首页 > 代码库 > python连接数据库

python连接数据库

使用pymysql:
//安装pymysql
pip install pymysql

 

代码:

# coding=utf8import pymysql# 创建连接对象conn = pymysql.connect(host=127.0.0.1, user=root, password=‘‘, db=school)# 创建游标cur = conn.cursor()# 查询数据库里某张表的内容def get_table():    cur.execute(SELECT name, address FROM teacher)    r = cur.fetchall()        print(r)    #get_table()# 执行sql,查询单条数据,并返回受影响行数effect_row = cur.execute("update teacher set name=‘alice‘ where id=1")#print(effect_row) #get_table()# 插入多条,并返回受影响的条数effect_rows = cur.executemany("insert into teacher(name, address)values(%s, %s)",                               [(aaa, a1), (bbb, b1), (ccc, c1)])#print(effect_rows)#get_table()# 获取最新自增idnew_id = cur.lastrowid#print(new_id)# 查询数据get_datas = cur.execute(SELECT * FROM teacher)# 获取一行#row_1 = cur.fetchone()#print(row_1)# 获取最多2行#row_2 = cur.fetchmany(2)#print(row_2)row_3 = cur.fetchall()print(row_3)#重设游标为字典类型cur = conn.cursor(cursor = pymysql.cursors.DictCursor)#提交,保存新建或修改的数据conn.commit()# 关闭游标cur.close()# 关闭连接conn.close()

 

python连接数据库