写操作:
#安装PyMySQL:pip3 install PyMySQL #!/usr/bin/python3 #coding=utf-8 import pymysql # 打开数据库连接 db = pymysql.connect("localhost","root","root","mypython" ) # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 插入语句 sql = """insert into user set name='zzz',pwd='cccdd',insert_time='13241'""" try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() #获取自增id new_id = cursor.lastrowid except: # 如果发生错误则回滚 db.rollback() # 关闭数据库连接 db.close() print(new_id)读操作单条:
#!/usr/bin/python3 import pymysql # 打开数据库连接 db = pymysql.connect("localhost","root","root","mypython" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor(cursor=pymysql.cursors.DictCursor) # 使用 execute() 方法执行 SQL 查询 cursor.execute("select * from user") # 使用 fetchone() 方法获取单条数据. data = cursor.fetchone() print (data) # 关闭数据库连接 db.close()读操作多条:
#!/usr/bin/python3 import pymysql # 打开数据库连接 db = pymysql.connect("localhost","root","root","mypython" ) # 使用cursor()方法获取操作游标 cursor = db.cursor(cursor=pymysql.cursors.DictCursor) # SQL 查询语句 sql = "SELECT * FROM user WHERE id > '%d'" % (0) try: # 执行SQL语句 cursor.execute(sql) # 获取所有记录列表 results = cursor.fetchall() print (results) except: print ("Error: unable to fetch data") # 关闭数据库连接 db.close()[{'id': 1, 'insert_time': 2147483647, 'pwd': 'ccc', 'name': 'zsc'}, {'id': 2, 'insert_time': 13241, 'pwd': 'cccdd', 'name': 'zzz'}]