首页 > 技术文章 > python3访问MySQL数据库

mghhzAnne 2019-03-11 14:28 原文

import pymysql
db = pymysql.connect(
    host='XXXXXXXX.com',     #数据库服务器地址

    user='XXX',              #用户名
    passwd='XXX',      
    db='db_test',           #数据库名(一个数据库服务器地址中可以包含多个数据库)
port=3306, charset
='utf8' ) cursor=db.cursor() str="INSERT INTO `the_XXXX` (`XXX`, `XXX`) VALUES (333323, NULL)" try: cursor.execute(str) db.commit() except: db.rollback() print("失败") db.close()

 上面是插入数据

cursor=db.cursor()
str="create table test(testname char(10),testnum int) "
try:
    cursor.execute(str)
    db.commit()
except:
     db.rollback()
     print("失败")

db.close()

上面是新建表

cursor=db.cursor()
str="select * from XXXX"
try:
    cursor.execute(str)
    db.commit()
    results=cursor.fetchall()
    for row in results:
        print(row)
except:
     db.rollback()
     print("失败")

db.close()

上面是查询

输入变量的话,就是将变量放进字符串,然后其他逻辑都一样,没什么跟python操作不一样的

 

报错信息:如果用户名或者密码错误会报1405:Access denied for user'XXX'

                 如果数据库名字错误会报1404:Access denied for user'XXX'  to database 'YYY'

                如果服务器地址错误会报2003:Can't connect to MySQL server on "www.XXXXXX.com"

推荐阅读