python-操作DB

2433 ワード

python --mysql
python3: pymysql python2: MySQLdb
手順:1、データベース接続オブジェクトdb=pymysqlを確立する.接続(「dbaddress」,「username」,「password」,「dbname」,「charset=「utf 8」)2で、カーソルオブジェクトcursor=dbを作成します.cursor()3は、カーソルオブジェクトの方法でデータベースcursorを操作する.execute("command;"); 4,commit dbをコミットする.commit(); 5カーソルオブジェクトcursorを閉じる.close()6、データベース接続dbを閉じる.close(); db接続オブジェクトがサポートする方法:1,cursor()カーソルオブジェクトの作成2,commit()コミット方法3,rollback()ロールバック方法4,close()接続を閉じる
Cursorオブジェクトサポートの方法:1,execute(「SQLコマンド」)SQLコマンド2,fetchone()取得結果セットの1番目のレコード3,fetchmany(n)取得結果セットのn番目のレコード4,fetchall()取得結果セットのすべてのレコード5,close()カーソルオブジェクトを閉じる
import pymysql

# python  mysql   :
# 1,        
# 2,       
# 3,               
# 4,   commit
# 5,       
# 6,        

try:
    #  db    
    db = pymysql.connect("192.168.10.16","wang","123456","wang",charset = "utf8")

    #      
    cursor = db.cursor()

    #cursor.execute("create database wang;")

    #            ,   use db
    cursor.execute("use wang;")

    #    
    # sql_create = "create table t3(id int auto_increment, name varchar(30) default '', age int default 0, score int default 0,primary key(id))engine = innodb;"
    # cursor.execute(sql_create)
    sql_insert = "insert into t3(name,age,score) values('llj',20,100),('wanghuan',18,99);"
    cursor.execute(sql_insert)

    #    
    sql_query = "select * from wang.t3 limit 5;"

    #      ;   ,      cursor 
    cursor.execute(sql_query)


    #          ,   
    data = cursor.fetchall()
    print("      :")
    for I in data:
        print(I)

    #    ,     ,   rollback()
    db.commit()

finally:
    #    
    cursor.close()
    db.close()
import pymysql

host = "192.168.10.16"
user = "wang"
password = "123456"
dbname = "wang"
ch = "utf8"

db = pymysql.connect(host, user, password, dbname, charset = ch)
cur = db.cursor()

try:
    sql_update_1 = "update t3 set age = age + 1 where name = 'llj';"
    sql_update_2 = "update t3 set age = age + 2 where name = 'wanghuan';"
    cur.execute(sql_update_1)
    cur.execute(sql_update_2)
    db.commit()

    print("execute successfully;")

except Exception as e:
    db.rollback()
    print("execute failed, command has been rollback")

cur.close()
db.close()