使用python3操作mysql数据库

因为使用的python3.6,所以需要载入pymysql库,需要注意的是,python2和python3载入的库是不一样的。
pymysql.Connect( host, port, user, passwd, db, charset )
如:
host = “localhost”,
port = 3306,
user = “root”,
passwd = “root”,
db = “pachong”,
charset = “utf8”
connect主要负责连通数据库。真正操作数据库,需要使用游标cursor:
cursor = conn.cursor()

# -*- coding: utf-8 -*-

import pymysql

conn = pymysql.Connect( 
        host = "localhost",
        port = 3306,
        user = "root",
        passwd = "root",
        db = "pachong",
        charset = "utf8"
        )

cursor = conn.cursor()

sql = "select * from question"
try:
    cursor.execute( sql )
    print( cursor.rowcount )
    
    res = cursor.fetchall()
    print( res )
    
    for line in res:
        print( "第%d条,问题是:%s"%( line[0], line[1] ) )
    
    conn.commit()
    '''
    res = cursor.fetchone()
    print( res )
    
    res = cursor.fetchmany( 2 )
    print( res )
    '''
except Exception as e:
    print( e )
    conn.rollback()
conn.close()
cursor.close()

需要记得操作完数据库,要记得关闭connext(),cursor()

# -*- coding: utf-8 -*-

import pymysql

conn = pymysql.Connect( 
        host = "localhost",
        port = 3306,
        user = "root",
        passwd = "root",
        db = "pachong",
        charset = "utf8"
        )

cursor = conn.cursor()
try:
    sql_insert = "insert into question( question_content ) values( '如何才能开开心心' )"
    #sql_update = "update question set question_content = '已修改,如何才能开开心心' where question_id = 5"
    #sql_delete = "delete from question where queston_id = 1"
    #cursor.execute( sql_insert )
    #print( "影响行数:"+cursor.rowcount, "最后一个的主键:"+cursor.lastrowid )
    #conn.commit()
except Exception as e:
    print( e )
    conn.rollback()
    
cursor.close()
conn.close()

你可能感兴趣的:(日常总结)