python操作mysql插入数据
- 首先安装pymysql这个库
- pycharm连接数据库
- 操作mysql语句
- 连接数据库
- 插入数据
由于有时候,数据存在excel表格中,需要借助python去读取数据然后再插入到数据库中
首先安装pymysql这个库
pycharm连接数据库
这一步可要可不要,虽然那个sql语句会报红,但是其实运行起来也不会报错,连接了过后,pycharm会连接到那个数据库,可以识别插入语句,也就不会报红了
操作mysql语句
连接数据库
def db_connect():connection = pymysql.connect(host='localhost',user='root',password='123456',database='charge',charset="utf8")connection.select_db('charge') #选择数据库# print(connection)return connection
插入数据
当然也有创建数据库这些操作,都要自己写sql语句,然后直接使用cusor.execute直接使用该语句即可
def db_insert(connection,data):cusor = connection.cursor() # 使用 cursor() 方法创建一个游标对象 cursor,cursor返回一个游标实例对象,其中包含了很多操作数据的方法# insert=cusor.executemany(sql,[(4,'wen',20),(5,'tom',10),(6,'test',30)]) 多行插入sqlWord = "insert into charge_record values(%s,%s,%s,%s,%s,%s,%s,%s)" #sql语句sqlWord1 = "insert into charge_record values(null,'root','2021/12/1 21.01', '饮料', '饮食', '副食', '4.0', '')"# cusor.execute(sqlWord1)# cusor.execute(sqlWord,(null,'root','2021/12/1 21.01', '饮料', '饮食', '副食', '4.0', ''))#以上为单行插入try:# cusor.execute(sqlWord1)# print(1)cusor.executemany(sqlWord,data) #data是你的数据,列表套元祖,例子:[('1'),('2'),('3')]cusor.connection.commit() #如果成功,则commit,connection.commit()也可以直接这样except Exception as e: connection.rollback() #如果错误,回滚操作print(e)print("失败")finally:connection.close() #操作完过后都要去关闭连接