TypeError: __init__() takes 1 positional argument but 6 were given

数据库连接错误:

TypeError: __init__() takes 1 positional argument but 6 were given

任务:向win_2022数据库中的zard表里插入数据。 

做如下代码:

#任务:插入数据
import pymysql

db = pymysql.connect("localhost","root",'lkw,747477910','win_2022') #打开数据库连接
cursor = db.cursor() #使用cursor()方法获取游标操作
#编写SQL语句
sql = "insert into zard (name,major,hobby,value,ziduan) value ('%s','%s','%s','%s','%s')" %("坂井泉水","歌手",'摇滚乐',"23","不要认输")

try:
    cursor.execute(sql) #执行sql语句
    db.commit() #提交事务
except:
    db.rollback()
db.close() #关闭数据库连接

运行报错:

TypeError: __init__() takes 1 positional argument but 6 were given_第1张图片

检验该错误,判段为连接数据库出错,同:

#检验连接数据库是否成功
import pymysql

dbhost='localhost'
dbuser='root'
dbpass='lkw,747477910'
dbname='win_2022'

try:
    db=pymysql.connect(dbhost,dbuser,dbpass,dbname)
    print("数据库连接成功")
except pymysql.Error as e:
    print("数据库连接失败:"+str(e))

TypeError: __init__() takes 1 positional argument but 6 were given_第2张图片

更正:

try:
    #db=pymysql.connect(dbhost,dbuser,dbpass,dbname)  #这里为什么不对
    db = pymysql.connect(host=dbhost, user=dbuser, password=dbpass, database=dbname)
    print("数据库连接成功")
except pymysql.Error as e:
    print("数据库连接失败:"+str(e))

总结:第一种传递参数的方式为位置传参,容易出错,用第二种传参(关键字参数)就不那么容易错了。 

由上更正“插入数据”任务代码为:

#任务:插入数据
import pymysql

#打开数据库连接
try:
    #db = pymysql.connect("localhost","root","lkw,747477910","win_2022")  #这里为什么不对
    db = pymysql.connect(host="localhost",user="root",password='lkw,747477910',database='win_2022')
    print("数据库连接成功")
except pymysql.Error as e:
    print("数据库连接失败:"+str(e))

cursor = db.cursor() #使用cursor()方法获取游标操作
#编写SQL语句
sql = "insert into zard (name,major,hobby,value,ziduan) value ('%s','%s','%s','%s','%s')" %("坂井泉水","歌手",'摇滚乐',"23","不要认输")

try:
    cursor.execute(sql) #执行sql语句
    db.commit() #提交事务
except:
    db.rollback()
db.close() #关闭数据库连接

运行成功: 

TypeError: __init__() takes 1 positional argument but 6 were given_第3张图片

感悟:对于没有把握写对的代码,要善于利用try语句抛出异常。

 

你可能感兴趣的:(python错误处理归纳,数据库,sql,database)