Python---mysql 连接及操作
一:准备工作(创建数据库)
二:在python中连接数据库并操作
pip install pymysql # 安装第三方库
# 连接mysql数据库,做数据库存储 import pymysql # 连接数据库 connection_fanmao = pymysql.Connection( host='localhost', port=3306, user='root', password='****', db='fanmao36') # 创建游标,游标可以用来帮我们执行sql cursor = connection_fanmao.cursor() # 读操作:查询sql 使用cursor.fetchall() 获取查询结果 sql_select_1 = cursor.execute("select version()") # 执行sql语句 r = cursor.fetchall() # 使用游标获取sql执行结果,一般返回的结果是二维元组 print('mysql版本:',r) # 创建表(执行一次即可) sql_create_table = "CREATE TABLE student (id INT PRIMARY key NOT NULL,c_name varchar (64),age INT) " create_table_student = cursor.execute(sql_create_table) connection_fanmao.commit() # 写操作:增加,修改,删除 执行完成之后,需要commit() 提交事务 sql_insert_1 = cursor.execute("INSERT INTO student VALUES ('1', '张三', '20')") sql_insert_2 = cursor.execute("INSERT INTO student VALUES ('2', '李四', '21')") sql_insert_3 = cursor.execute("INSERT INTO student VALUES ('3', '王二', '22')") sql_update_1 = cursor.execute("UPDATE student SET `c_name`='张三哈哈哈哈' WHERE id=1") sql_delete_1 = cursor.execute("delete from student where id=2") connection_fanmao.commit() # 提交事务 # 读操作:查询sql sql_select_2 = cursor.execute("SELECT * FROM student") r = cursor.fetchall() print('student表查询数据:',r) # 收尾阶段 cursor.close() # 关闭游标 connection_fanmao.close() # 关闭连接
运行结果:
数据库中内容: