#coding=utf-8
import MySQLdb
if __name__ == "__main__":
db = MySQLdb.connect(host=<span style="color:#FF0000;">'localhost'</span>,
port=3306,
user='root',
passwd=XX',
db='XX')
cursor = db.cursor()
sql = "select * from student"
cursor.execute(sql)
for line in cursor.fetchall():
print line
db.close()
运行时出现如下错误:
[plain] view plaincopy
pydev debugger: starting
Traceback (most recent call last):
File "C:\Program Files\aptan3\plugins\org.python.pydev_2.6.0.2012062121\pysrc\pydevd.py", line 1392, in <module>
debugger.run(setup['file'], None, None)
File "C:\Program Files\aptan3\plugins\org.python.pydev_2.6.0.2012062121\pysrc\pydevd.py", line 1085, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "D:\Aptana Studio 3 Workspace\first\com\lin\test01.py", line 9, in <module>
db='netbase')
File "E:\python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "E:\python27\lib\site-packages\MySQLdb\connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")
把host="localhost" 改为 host="127.0.0.1"就可以了
[python] view plaincopy
#coding=utf-8
import MySQLdb
if __name__ == "__main__":
db = MySQLdb.connect(<span style="color:#FF0000;">host='127.0.0.1',</span>
port=3306,
user='root',
passwd=XX',
db='XX')
cursor = db.cursor()
sql = "select * from student"
cursor.execute(sql)
for line in cursor.fetchall():
print line
db.close()
运行如下:
[plain] view plaincopy
pydev debugger: starting
('lin', 88L)
('cjm', 8L)
Django + MySQLdb + Mysql settings 文件数据库设置:
[plain] view plaincopy
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'mydb', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': 'root',
'PASSWORD': 'mydb',
#'HOST': '',
'HOST': '127.0.0.1', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '3306', # Set to empty string for default.
}
}
然后连接数据库:
[plain] view plaincopy
import sys; print('%s %s' % (sys.executable or sys.platform, sys.version))
PyDev console: using default backend (IPython not available).
E:\python27\python.exe 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]
from django.core import management;import netbase.settings as settings;management.setup_environ(settings)
u'D:\\Aptana Studio 3 Workspace\\netbase\\netbase'
from django.db import models
from django.db import connection
cursor = connection.cursor()
--转自