import pymysql conn = pymysql.connect( host="127.0.0.1", # ip地址 port=3306, # 端口位置 user="root", # 用户名 password="123", # 密码 database="nash", # 数据库名 charset="utf8", # 当前数据库编码格式 autocommit=True # 是否设置自动commit确认 ) cursor = conn.cursor(pymysql.cursors.DictCursor)
import pymysql # 打开数据库链接 db = pymysql.connect("localhost", "testuser", "test123", "TESTDB") # 使用 cursor() 方法建立一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL,若是表存在则删除 cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") # 使用预处理语句建立表 sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )""" cursor.execute(sql) # 关闭数据库链接 db.close()
import pymysql # 打开数据库链接 db = pymysql.connect("localhost", "testuser", "test123", "TESTDB") # 使用cursor()方法获取操做游标 cursor = db.cursor() # SQL 插入语句 sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)""" try: cursor.execute(sql) # 执行sql语句 db.commit() # 提交到数据库执行 except: db.rollback() # 若是发生错误则回滚 # 关闭数据库链接 db.close()
Python查询Mysql使用 fetchone() 方法获取单条数据,使用python
fetchmany(参数)
:获取指定参数条数据。fetchone()
: 该方法获取下一个查询结果集。结果集是一个对象fetchall()
: 接收所有的返回结果行.rowcount()
: 这是一个只读属性,并返回执行execute()方法后影响的行数。import pymysql # 打开数据库链接 db = pymysql.connect("localhost", "testuser", "test123", "TESTDB") # 使用cursor()方法获取操做游标 cursor = db.cursor() # SQL 查询语句 sql = "SELECT * FROM EMPLOYEE \ WHERE INCOME > %s" % (1000) try: cursor.execute(sql) # 执行SQL语句 results = cursor.fetchall() # 获取全部记录列表 for row in results: fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4] # 打印结果 print ("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \ (fname, lname, age, sex, income )) except: print("Error: unable to fetch data") # 关闭数据库链接 db.close()
import pymysql # 打开数据库链接 db = pymysql.connect("localhost", "testuser", "test123", "TESTDB") # 使用cursor()方法获取操做游标 cursor = db.cursor() # SQL 更新语句 sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M') try: cursor.execute(sql) # 执行SQL语句 db.commit() # 提交到数据库执行 except: db.rollback() # 发生错误时回滚 # 关闭数据库链接 db.close()
import pymysql # 打开数据库链接 db = pymysql.connect("localhost", "testuser", "test123", "TESTDB") # 使用cursor()方法获取操做游标 cursor = db.cursor() # SQL 删除语句 sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20) try: cursor.execute(sql) # 执行SQL语句 db.commit() # 提交修改 except: db.rollback() # 发生错误时回滚# 关闭链接 db.close()