Python3中使用Mysql的用法。


一、Python2中一般使用MySqldb来调用Mysql,但是在Python3中不支持该包,使用pymysql来代替了,用法一模一样。

二、安装:

pip install pymysql

三、例子:

#coding utf-8
import pymysql
try:
    conn = pymysql.connect(host='localhost',user="root",password='123456',database='datarepair',port=3306,charset='utf8')
    cursor = conn.cursor()
    #cursor.execute("select rowId,Name from ruletab where ruletype=%s",(10))
    cursor.executemany("select rowId,Name from ruletab where ruletype=%s",[10,20]) #一般用于批量增删改中。
    print(cursor.rowcount,cursor.rownumber)
    for x in cursor.fetchall():
        print("rowId:{0[0]} Name:{0[1]} RowNumber:{1}".format(x,cursor.rownumber))
    print('-' * 50)
    for x in cursor.fetchmany(2):
        print("rowId:{0[0]} Name:{0[1]} RowNumber:{1}".format(x,cursor.rowcount))
    print('-' * 50)
    cursor.scroll(0,'absolute') #将游标调回0位置处。
    for x in cursor.fetchmany(2):  #取2条记录。
        print("rowId:{0[0]} Name:{0[1]} RowNumber:{1}".format(x,cursor.rownumber))
    print(cursor.rowcount,cursor.rownumber)
    cursor.close()


finally:
    if 'conn' in dir() and callable(conn) and conn.open:
        conn.close()
        print("closed successfully.")

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM