python对数据库的操作

首先引入模块

py文件中引入pymysql

from pymysql import *

Connection 对象

用于建立与数据库的连接

创建对象:调用connect()方法

conn=connect(参数列表)

· 参数host接的mysql主机IP,如果本机是'localhost'

· 参数port接的mysql主机的端口,默3306

· 参数database:数据的名称

· 参数user接的用

· 参数password接的密

· 参数charset:通信采用的编码方式,推荐使用utf8

cursor游标对象

cursor1 = con.cursor()

count = cursor1.execute(sql语句)  # 返回查到的数据个数

cursor1.fetchone() # 获取一个数据

cursor1.fetchmany(5) # 获取多个数据

cursor1.fetchall()  # 获取所有数据

任务结束后关闭cursor,connect

con.close( )

cursor1.close( )


例如:

# 1、导入pymysql
from pymysql import *

# 2、创建连接对象
con = connect(host= '192.168.205.132',port = 3306,user = 'root', password ='mysql',
        database = 'School',charset = 'utf8')

# 3、创建游标对象 cursor
cursors = con.cursor()

# 4、执行sql
sql = "select * from goods"

# 5、执行sql语句  execute:执行
# 返回受影响的行数
count = cursors.execute(sql)

# fetch:获取、获得---->get
# fetchone一次只拿一条数据
# for i in range(count):
#     print(cursors.fetchone())

#fetchmany 获取指定条数的数据
# for i in cursors.fetchmany(5):
#     print(i)
# print(cursors.fetchmany(5))

#fetchall 获取全部数据
for i in cursors.fetchall():
    print(i)

print(count)

# 6、关闭游标对象
cursors.close()

# 7、关闭连接对象
con.close()

数据的增加删除修改!!!!!!!!!!!

其实很简单,我们只需修改mysql语句

例如插入数据:

sql = "insert into goods_brands values(0,'微软')"

例如修改数据:

sql = "update goods_brands set name='内涵段子' where id = 18"

例如删除数据:

sql = "delete from goods_brands where id = 18"

但是注意最后要加上con.commit()把数据提交,这是pymsql的一个功能,防止误操作,只有确认提交才会真正修改数据库


猜你喜欢

转载自blog.csdn.net/weixin_31449201/article/details/80377881