美文网首页
Python 连接数据库 (2020-04-03)

Python 连接数据库 (2020-04-03)

作者: 似海深蓝 | 来源:发表于2020-04-03 16:39 被阅读0次

1. 连接MySQL

# 导包(pymysql) -> pymysql.connect() -> con.cursor() -> cur.execute(sql) -> cur.fetch***()

# 1. import pymysql
# 2. 建路connect()
con = pymysql.connect(host = "",port = ,user = "",password = "",charset = "utf8")
# 3. 建车 路.cursor()
cur = con.cursor()
# 4.传输
cur.execute("show databases") 

# 5.展示,注意:每次fetch一个都少一个或对应的个数
# 分别执行情况:每次执行前都execute一次
>>> cur.fetchall()
输出:(('information_schema',),
     ('mysql',),
     ('performance_schema',),
     ('python_test1',),
     ('python_test2',),
     ('python_test3',),
     ('sys',))
>>> cur.fetchmany(3)
(('information_schema',), ('mysql',), ('performance_schema',))
>>> cur.fetchone()
('information_schema',)

# 依次执行:只execute一次
>>> cur.fetchone()
('information_schema',)
>>> cur.fetchmany(3)
(('mysql',), ('performance_schema',),('python_test1'))
>>> cur.fetchall()
(('python_test2',),('python_test3',),('sys',))

2. 增删改查

2.1 每次execute只能传输一条sql语句
2.2 对表进行增删改要提交事务

当我们使用cursor.execute(SQL)执行一(多)条Insert/Update/Delete语句后,
我们需要使用conn.commit()提交事务,否则,语句不会生效。

#1. 栗子
sql11 = '''
        insert into fruits1(f_id,s_id,f_name,f_price)
        values
        ('b12',101,'blackberry',10.2),
        ('bs12',102,'orange',11.2),
        ('bs22',105,'melon',8.2),
        ('t12',102,'banana',10.3),
        ('t22',102,'grape',5.3)
        '''
sql12 = "update fruits1 set f_price = 25.7 where f_id = 'a2' "


cur.execute(sql11)
cur.execute(sql12) #此时数据库并没有更改
con.commit() #此时才两条一起运行

#2. 注意,多条语句一起执行最好放在try里
try:
   # 执行sql语句
   cursor.execute(sql)
   # 提交到数据库执行
   con.commit()
except:
   # Rollback in case there is any error
   con.rollback()
   # print("回滚")

3.关闭

cursor.close()
connect.close()

相关文章

网友评论

      本文标题:Python 连接数据库 (2020-04-03)

      本文链接:https://www.haomeiwen.com/subject/ylqkphtx.html