我的问题:使用带有参数的python(2.x)MySQLdb模块创建数据库时,我会获得拒绝访问或语法无效,具体取决于我引用数据库的方式名。
示例(没有参数,显示它正在工作):
$ python
Python 2.7.5 (default, Jun 24 2015, 00:41:19)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>> MySQLdb.version_info
(1, 2, 5, 'final', 1)
>>> db = MySQLdb.connect(user='user', passwd='pass')
>>> c = db.cursor()
>>> c.execute("CREATE DATABASE IF NOT EXISTS foo")
>>> c.fetchall()
()
带参数且没有引号:
>>> c.execute("CREATE DATABASE IF NOT EXISTS %s", ('foo', ))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 205, in execute
File "build/bdist.linux-x86_64/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''foo'' at line 1")
使用参数和双引号(我尝试了各种组合):
>>> c.execute('''CREATE DATABASE IF NOT EXISTS %s''', ('foo', ))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 205, in execute
File "build/bdist.linux-x86_64/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''foo'' at line 1")
使用反引号,它给了我访问被拒绝,这真让我困惑:
>>> c.execute('''CREATE DATABASE IF NOT EXISTS `%s` ''', ('foo', ))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 205, in execute
File "build/bdist.linux-x86_64/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
_mysql_exceptions.OperationalError: (1044, "Access denied for user 'user'@'localhost' to database ''foo''")
我做错了什么?
这就是我创建用户的方式:
$ mysql -u root
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 1485
Server version: 5.5.44-MariaDB MariaDB Server
Copyright (c) 2000, 2015, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> grant usage, create, drop on foo.* to 'user'@'localhost' identified by 'pass' with grant option;
Query OK, 0 rows affected (0.00 sec)
MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.00 sec)