- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
错误是
File "c:\python27\lib\site-packages\MySQLdb\connections.py", line 72, in Connection
db = get_db_connection(db_name)
NameError: name 'get_db_connection' is not defined
所以我认为错误在 * 这是因为 def init(self, *args, **kwargs): 以冒号结尾但我不不知道连接的语法。
这是我在 connection.py 中的类连接代码
class Connection(_mysql.connection):
"""MySQL Database Connection Object"""
default_cursor = cursors.Cursor
def __init__(self, *args, **kwargs): # *** this is error I think ie the : but what is syntax
def get_db_connection(database_name):
db = MySQLdb.connect('localhost', 'user', 'pswrd', database_name)
cur = db.cursor()
return db, cur
db_name = 'test' # database name
user_name = 'root' # name of a user
db = get_db_connection(db_name)
"""
Create a connection to the database. It is strongly recommended
that you only use keyword parameters. Consult the MySQL C API
documentation for more information.
host
string, host to connect
user
string, user to connect as
passwd
string, password to use
db
string, database to use
port
integer, TCP/IP port to connect to
unix_socket
string, location of unix_socket to use
conv
conversion dictionary, see MySQLdb.converters
connect_timeout
number of seconds to wait before the connection attempt
fails.
compress
if set, compression is enabled
named_pipe
if set, a named pipe is used to connect (Windows only)
init_command
command which is run once the connection is created
read_default_file
file from which default client values are read
read_default_group
configuration group to use from the default file
cursorclass
class object, used to create cursors (keyword only)
use_unicode
If True, text-like columns are returned as unicode objects
using the connection's character set. Otherwise, text-like
columns are returned as strings. columns are returned as
normal strings. Unicode objects will always be encoded to
the connection's character set regardless of this setting.
charset
If supplied, the connection character set will be changed
to this character set (MySQL-4.1 and newer). This implies
use_unicode=True.
sql_mode
If supplied, the session SQL mode will be changed to this
setting (MySQL-4.1 and newer). For more details and legal
values, see the MySQL documentation.
client_flag
integer, flags to use or 0
(see MySQL docs or constants/CLIENTS.py)
ssl
dictionary or mapping, contains SSL connection parameters;
see the MySQL documentation for more details
(mysql_ssl_set()). If this is set, and the client does not
support SSL, NotSupportedError will be raised.
local_infile
integer, non-zero enables LOAD LOCAL INFILE; zero disables
There are a number of undocumented, non-standard methods. See the
documentation for the MySQL C API for some hints on what they do.
"""
from MySQLdb.constants import CLIENT, FIELD_TYPE
from MySQLdb.converters import conversions
from weakref import proxy, WeakValueDictionary
import types
kwargs2 = kwargs.copy()
if 'conv' in kwargs:
conv = kwargs['conv']
else:
conv = conversions
conv2 = {}
for k, v in conv.items():
if isinstance(k, int) and isinstance(v, list):
conv2[k] = v[:]
else:
conv2[k] = v
kwargs2['conv'] = conv2
cursorclass = kwargs2.pop('cursorclass', self.default_cursor)
charset = kwargs2.pop('charset', '')
if charset:
use_unicode = True
else:
use_unicode = False
use_unicode = kwargs2.pop('use_unicode', use_unicode)
sql_mode = kwargs2.pop('sql_mode', '')
client_flag = kwargs.get('client_flag', 0)
client_version = tuple([ numeric_part(n) for n in _mysql.get_client_info().split('.')[:2] ])
if client_version >= (4, 1):
client_flag |= CLIENT.MULTI_STATEMENTS
if client_version >= (5, 0):
client_flag |= CLIENT.MULTI_RESULTS
kwargs2['client_flag'] = client_flag
super(Connection, self).__init__(*args, **kwargs2) #****
self.cursorclass = cursorclass
self.encoders = dict([ (k, v) for k, v in conv.items()
if type(k) is not int ])
self._server_version = tuple([ numeric_part(n) for n in self.get_server_info().split('.')[:2] ])
db = proxy(self)
def _get_string_literal():
def string_literal(obj, dummy=None):
return db.string_literal(obj)
return string_literal
def _get_unicode_literal():
def unicode_literal(u, dummy=None):
return db.literal(u.encode(unicode_literal.charset))
return unicode_literal
def _get_string_decoder():
def string_decoder(s):
return s.decode(string_decoder.charset)
return string_decoder
string_literal = _get_string_literal()
self.unicode_literal = unicode_literal = _get_unicode_literal()
self.string_decoder = string_decoder = _get_string_decoder()
if not charset:
charset = self.character_set_name()
self.set_character_set(charset)
if sql_mode:
self.set_sql_mode(sql_mode)
if use_unicode:
self.converter[FIELD_TYPE.STRING].append((None, string_decoder))
self.converter[FIELD_TYPE.VAR_STRING].append((None, string_decoder))
self.converter[FIELD_TYPE.VARCHAR].append((None, string_decoder))
self.converter[FIELD_TYPE.BLOB].append((None, string_decoder))
self.encoders[types.StringType] = string_literal
self.encoders[types.UnicodeType] = unicode_literal
self._transactional = self.server_capabilities & CLIENT.TRANSACTIONS
if self._transactional:
# PEP-249 requires autocommit to be initially off
self.autocommit(False)
self.messages = []
def cursor(self, cursorclass=None):
"""
Create a cursor on which queries may be performed. The
optional cursorclass parameter is used to create the
Cursor. By default, self.cursorclass=cursors.Cursor is
used.
"""
return (cursorclass or self.cursorclass)(self)
def __enter__(self): return self.cursor()
def __exit__(self, exc, value, tb):
if exc:
self.rollback()
else:
self.commit()
def literal(self, o):
"""
If o is a single object, returns an SQL literal as a string.
If o is a non-string sequence, the items of the sequence are
converted and returned as a sequence.
Non-standard. For internal use; do not use this in your
applications.
"""
return self.escape(o, self.encoders)
def begin(self):
"""Explicitly begin a connection. Non-standard.
DEPRECATED: Will be removed in 1.3.
Use an SQL BEGIN statement instead."""
from warnings import warn
warn("begin() is non-standard and will be removed in 1.3",
DeprecationWarning, 2)
self.query("BEGIN")
if not hasattr(_mysql.connection, 'warning_count'):
def warning_count(self):
"""Return the number of warnings generated from the
last query. This is derived from the info() method."""
from string import atoi
info = self.info()
if info:
return atoi(info.split()[-1])
else:
return 0
def set_character_set(self, charset):
"""Set the connection character set to charset. The character
set can only be changed in MySQL-4.1 and newer. If you try
to change the character set from the current value in an
older version, NotSupportedError will be raised."""
if charset == "utf8mb4":
py_charset = "utf8"
else:
py_charset = charset
if self.character_set_name() != charset:
try:
super(Connection, self).set_character_set(charset)
except AttributeError:
if self._server_version < (4, 1):
raise NotSupportedError("server is too old to set charset")
self.query('SET NAMES %s' % charset)
self.store_result()
self.string_decoder.charset = py_charset
self.unicode_literal.charset = py_charset
def set_sql_mode(self, sql_mode):
"""Set the connection sql_mode. See MySQL documentation for
legal values."""
if self._server_version < (4, 1):
raise NotSupportedError("server is too old to set sql_mode")
self.query("SET SESSION sql_mode='%s'" % sql_mode)
self.store_result()
def show_warnings(self):
"""Return detailed information about warnings as a
sequence of tuples of (Level, Code, Message). This
is only supported in MySQL-4.1 and up. If your server
is an earlier version, an empty sequence is returned."""
if self._server_version < (4,1): return ()
self.query("SHOW WARNINGS")
r = self.store_result()
warnings = r.fetch_row(0)
return warnings
Warning = Warning
Error = Error
InterfaceError = InterfaceError
DatabaseError = DatabaseError
DataError = DataError
OperationalError = OperationalError
IntegrityError = IntegrityError
InternalError = InternalError
ProgrammingError = ProgrammingError
NotSupportedError = NotSupportedError
errorhandler = defaulterrorhandler
这是调用该函数的 connection.py 中的第 187 行
super(Connection, self).__init__(*args, **kwargs2) #****
最佳答案
来自 Connection.__init__
文档字符串 - 强烈建议您仅使用关键字参数。
尝试使用类似的东西:
MySQLdb.connect(
host='localhost',
user='user',
passwd='pswrd',
db=database_name
)
此外,发布您遇到的错误。这可能会有所帮助。
关于python - 如何使用mysqldb进行本地mysql连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14914227/
我已经尝试了很多方法来解决这个问题,但我没有解决。我在 google 和 stackoverflow 上搜索了很多,没有适合我的选项。请帮我。提前致谢。我正在使用 django 1.10,python
我正在尝试启动一个 Django 项目。 我在尝试运行 manage.py 时遇到此错误: (venv)dyn-160-39-161-214:proj Bren$ python manage.py T
我正在尝试启动一个 Django 项目。 我在尝试运行 manage.py 时遇到此错误: (venv)dyn-160-39-161-214:proj Bren$ python manage.py T
所以我在我的 Linux 上安装了 Mysql。之后,我使用命令 sudo apt-get install python-mysqldb 安装了 mysqldb。然后,当我尝试在 python 中导入
我正在尝试通过 Python 的 MySQLdb 库将数据从 Pandas(从 CSV 导入)传递到 MySQL 数据库。当文字反斜杠发挥作用时,我遇到了麻烦。我从原始输入中转义了单个反斜杠,因此 P
我在 Win7 上使用 Django 1.4.1 和 Active Python 2.7。我已经使用 pypm install mysql-python 安装了 MySQL 模块。 数据库引擎是dja
我正在开发一个 Google App Engine 项目,在尝试使用 MySQL 设置基本 Django 管理站点时遇到了问题。我已经搜索过这个问题,但我看到的都是人们发布有关在本地运行应用程序的交易
我是 Python 的新手,正在尝试设置 Django 项目以使用 MySql。我已经通读了文档以及有关该主题的其他一些 StackOverflow 帖子,但我仍然无法让它发挥作用。 当我尝试在 Dj
username@servername 11 月 2 日星期二 22:08:28 ~/public_html/IDM_app $ sudo aptitude install mysql-server
我创建了一个使用 MySQL 数据库的 Django 项目。我在 mysql 安装工具中有 mysql-python 连接器。我不确定我是否在环境变量中设置了必需的路径。当我运行服务器时,它引发错误:
我无法连接 mysql,也无法对其执行“python manage.py syncdb” 如何在django和django-cms中连接mysql不报错? 最佳答案 用django连接mysql su
我在尝试连接到 mysql 数据库时遇到的问题。我还给出了我使用的数据库设置。 Traceback (most recent call last): File "manage.py", line
我知道这个错误发生在很多人身上,我尝试了不同的解决方案,但都没有奏效。 我正在使用 aws eb cli。 我正在使用以下命令 eb deploy将我的应用程序部署到服务器。 以下是我的 Django
所以我安装了 Bitnami Django 堆栈,希望能像所宣称的“可立即运行”版本的 python 和 mysql 一样。但是,我无法让 python 同步数据库:“加载 MySQLdb 模块时出错
这将是我一生中第二次发布几乎完全相同的事情。这次和上次相差了大约9个月,学习过程非常困难,而且在过去的9个月里我从来没有遇到过这个问题,并且在整个时间段内经常完美地使用MySQLdb。我认识到类似的问
win10python3.7.3安装了mysqlclient1.4.2 当我导入 mysqlclient 时,运行代码时收到错误消息。当我安装mysqlclient时,我将'mysqlclient-1
我正在 EC2 Amazon-Linux 实例上设置我的网站,它使用一些 Python。 经过大量调整后,我在设置 Python 时遇到了很大的麻烦。特别是下面的代码会抛出错误: >>> impor
我正在阅读有关事务如何在 python 的 MySQLdb 中工作的信息。在 this tutorial ,它说: In Python DB API, we do not call the BEGIN
我一直在尝试使用 pip install flask-mysqldb 安装 flask-mysqldb,但每次我尝试它都会给我一个错误提示: error: command 'C:\Program Fi
我想在重复输入时退出程序,这是我所做的没有成功的事情: 我想处理该错误,但不知道如何并且尚未找到有关它的信息。 def connection(): global servername, use
我是一名优秀的程序员,十分优秀!