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