Python连接到MySQL错误

Python connect to MySQL error

当我想将python与mysql连接时,为什么我总是得到这个错误TypeError: __init__() takes 1 positional argument but 2 were given

准确的错误代码是:

1
2
3
4
5
6
7
8
Traceback (most recent call last):
  File"cone.py", line 4, in
    conn = mysql.connector.connect(f)
  File"C:\Python34\lib\site-packages\mysql\connector\__init__.py", line 179, in connect
    return MySQLConnection(*args, **kwargs)
  File"C:\Python34\lib\site-packages\mysql\connector\connection.py", line 57, in __init__
    super(MySQLConnection, self).__init__(*args, **kwargs)
TypeError: __init__() takes 1 positional argument but 2 were given

以下是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
import mysql.connector

f="localhost","username","password","db"
conn = mysql.connector.connect(f)

c= conn.cursor()

c.execute("SELECT * FROM test")

rows=c.fetchall()

for eachRow in rows:
    print (eachRow)


如果您已经成功修复了mysqldb,那么您可以这样连接

1
2
3
4
5
6
7
8
import MySQLdb

mydb = MySQLdb.connect(host = 'localhost',user = 'flo',passwd = '********',db = 'yourdb')
cur = mydb.cursor()
command = cur.execute('SELECT * FROM yourtable')
results = cur.fetchall()

print (results)

在python3.4中,使用pymysql尝试相同的方法,

安装EDOCX1[0]

1
2
3
import pymysql
conn = pymysql.connect("localhost","dev","pwd","db_name")
cur = conn.cursor()

mysql.connector.connect中应该这样连接

1
conn = mysql.connector.connect(host="localhost",user="uname", password="mypwd", database="emp_db")

例如,

1
2
3
4
5
6
7
>>> conn = mysql.connector.connect(f)Traceback (most recent call last):
  File"<stdin>", line 1, in <module>
  File"/usr/lib/python2.7/dist-packages/mysql/connector/__init__.py", line 98, in connect
    return MySQLConnection(*args, **kwargs)
TypeError: __init__() takes exactly 1 argument (2 given)
>>> conn = mysql.connector.connect(host="localhost",user="uname", password="pwd", database="reposter$tutorial_database")
>>>

这是DOC


试试这个:

1
conn = mysql.connector.connect(host="host", user="username",   password ="pwd", database="db")