python3连接数据库

python3的连接数据库代码:

我用的是本地服务器的mysql来进行连接。

# encoding=utf-8
import  pymysql
# db= pymysql.connect(
#     host='root',
#     passwd='#####',
#     db="excel",
#     charset='utf8')
db = pymysql.connect("localhost","#####","######",charset='utf8')#里面分别是用户名和密码
cursor = db.cursor()
cursor.execute("use excel")
try:
    sql = "select * from test"
    cursor.execute(sql)
    data = cursor.fetchall()
    for re in data:
        num = re[0]
        name = re[1]
        sex = re[2]
        print(num,name,sex)
except:
    print("unable to get data")

try:
    sql = "insert into test values(1613200012,'yang','man')"
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()

db.close();

猜你喜欢

转载自blog.csdn.net/jiejieyuy/article/details/79606226