Python工作问题

首先将conda install pymysql 或者 conda install python_mysql 安装:

#引入pymysql模块。注意小写
import pymysql
#打开数据库连接。localhost为主机地址,root是mysql登陆名,123是登陆密码,pythondb是数据库名
conn = pymysql.connect("localhost","root","123","pythondb")
#使用cursor()方法获取操作游标,利用游标来进行相关的数据操作
cursor = conn.cursor()
 
#预定义sql语句。创建student数据库表
create_sql = "create table student(id varchar(8),name varchar(10),age tinyint,sex varchar(2))"
#执行sql语句
cursor.execute(create_sql)
 
try:
    #插入语句。%s为占位符
    cursor.execute('insert into student values (%s, %s, %s, %s)', ['201701','Tom',20,'M'])
    cursor.execute('insert into student values (%s, %s, %s, %s)', ['201702','Mary',22,'W'])
    #插入语句。有参sql的另一个传递方式。
    #三引号之间输入的内容将被原样保留,可避免繁杂的转义
    insert_sql = """insert into student values ('201703','Jack',19,'M')"""
    cursor.execute(insert_sql)
    #提交到数据库执行,不加commit,则无法提交到数据库
    #只有对数据库进行了增删改时需要提交数据库,查询不需要
    conn.commit()
except:
    #try语句块出错时则回滚
    conn.rollback()
#关闭数据连接
conn.close()

https://blog.csdn.net/u013107656/article/details/52245144

http://dblab.xmu.edu.cn/blog/1817-2/

 https://blog.csdn.net/junshan2009/article/details/75042056

你可能感兴趣的:(python)