我正在使用python-mysql db api将一些值插入到表名为python变量的表中.所以我写了下面的代码
DB_CURSOR.execute("""INSERT INTO %s (name,created_by,state,description,docs,admin_email,date_created) VALUES(%s,%s,%s,%s,%s,%s,%s)""", (hosts_table, hostname, created_by, state, description, docroot, admin_email, date_created))
Run Code Online (Sandbox Code Playgroud)
如您所见,表名在hosts_table变量中.问题是mysqldb引用了表名,我得到了一个mysql错误.当我真正使用表名时,它工作正常.我怎么能绕过这个?
我正在尝试从数组中向我的数据库插入记录:
for string in self.FinalMailsArray:
c.execute("""INSERT INTO table (email) VALUES(%s) """,(string))
Run Code Online (Sandbox Code Playgroud)
问题是,我希望字段电子邮件是唯一的,所以我在数据库中启用了它.当我开始插入时,我得到重复输入值的错误.
有没有办法我可以说,"如果抛出重复的错误,只需转到数组中的下一个字符串"?
与仅.fetchone()在while循环中调用相比,编写以下生成器函数是否有优势?如果是这样,那优势是什么?
谢谢。
def testf2():
db = connectToMysqlDB(None)
sql_statement = " ".join([
"select d.* ",
"from dr_snapshot d ",
"order by d.PremiseID asc, d.last_read asc; "])
sel_cur = db.cursor()
rc = sel_cur.execute(sql_statement)
loop_ok = True
while loop_ok:
meter_row = sel_cur.fetchone()
if meter_row:
yield meter_row
else:
loop_ok = False
yield None
for read_val in testf2():
print(read_val)
#Perform something useful other than print.
('610159000', 6, datetime.datetime(2012, 7, 25, 23, 0), 431900L, 80598726L)
('610160000', 6, datetime.datetime(2012, 7, 25, 23, 0), 101200L, 80581200L) …Run Code Online (Sandbox Code Playgroud) 我在python中使用mysqldb.
我需要为表格执行以下操作.
1) Lock
2) Read
3) Truncate the table
4) Unlock
Run Code Online (Sandbox Code Playgroud)
当我运行以下代码时,我得到以下错误.所以,我不确定如何锁定表格来读取它,然后截断表格.我需要确保没有其他连接读取数据.
asin_list = []
conn = MySQLdb.connect(host=parms['database']['operations']['host'],user=parms['database']['operations']['username'],passwd=parms['database']['operations']['password'],db=parms['database']['operations']['database'])
cursor = conn.cursor()
query = "LOCK TABLES asin_one_time_only READ"
cursor.execute(query)
print 'fu1'
query = """select asin FROM asin_one_time_only"""
cursor.execute(query)
rows = cursor.fetchall()
for row in rows:
asin_list.append(row[0])
print asin_list
print 'fu2'
query = "UNLOCK TABLES;"
cursor.execute(query)
conn.commit()
print 'fu3'
query = "LOCK TABLES asin_one_time_only WRITE"
cursor.execute(query)
query = """truncate table amz_one_time_only"""
cursor.execute(query)
conn.commit()
print 'fu3'
query = "UNLOCK TABLES;"
cursor.execute(query)
conn.commit() …Run Code Online (Sandbox Code Playgroud) 我已经通过XAMPP运行MySQL了,我还安装了用于安装python的MySQLdb.然而,我无法弄清楚如何使用我的XAMPP的MySQL for Python.每次执行python manage.py runserver它都会显示错误:
..2.4c1-py2.7-win32.egg.tmp\MySQLdb\connections.py", line 187, in __init__
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")
我是Python的新手,这些是settings.py文件中的设置:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'tester', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': 'password', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # …Run Code Online (Sandbox Code Playgroud) 我得到了上面提到的警告
在第1行截断"'username'列的数据
我正在为我的模型"suserprofile"获取此项,其中"username"是我在模型中首次列出的字段
我检查了max_length选项,这对我来说不是问题,如果我在我的模型中更改了我的字段的顺序(将"email_id"字段更改为模型列表中的第一个),那么我收到警告替换'username'我在模型中首先提到的任何字段(在本例中为email_id).
我在运行syncdb时没有收到此警告,但只有在我尝试使用django通过实际运行本地浏览器在我的views.py文件中保存模型中的新对象("suserprofile")时才会收到警告.我不明白为什么会这样
编辑:
我的模特:
class SUserProfile(models.Model):
email_id = models.EmailField(max_length=30)
username = models.CharField(max_length=50,blank=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
Run Code Online (Sandbox Code Playgroud)
我的看法
from django.allauth.models import SocialAccount
def profileview(request):
user=request.user
if user.is_authenticated:
a=SocialAccount.objects.filter(user=user)
try:
f=a.get(provider='facebook')
except:
f=None
if f:
fusername=f.get_provider_account
fdata=f.extra_data
ffirst_name=fdata['first_name']
flast_name=fdata['last_name']
femail=fdata.get('email')
try:
old_user=SUserProfile.objects.get(email_id=femail)
except:
new_user=SUserProfile(
username=fusername,
email_id=femail,
first_name=ffirst_name,
last_name=flast_name,)
new_user.save()
Run Code Online (Sandbox Code Playgroud)
我在运行浏览器时收到的警告详细信息:
Exception Type: Warning
Exception Value: Data truncated for column 'email_id' at row 1
Exception Location:/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py in _warning_check, line 92
Traceback Switch to …Run Code Online (Sandbox Code Playgroud) 作为更大调试工作的一部分,我使用mysqldb遇到了以下错误:
File "x.py" line x, in method
cursor.close()
File "y.py" line 100, in close
while self.nextset(): pass
File "z.py" line 137, in nextset
self._waring_check()
...
Exception _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now") in <bound method Cursor.__del__ of <MySQLdb.cursor.Cursor object at 0x000002373198>> ignored
Run Code Online (Sandbox Code Playgroud)
我的代码的相关部分如下:
connection = mysqldb.connect('localhost', 'root', 'password', 'db')
cursor = connection.cursor()
file = open(filename, 'r')
sql = s = " ".join(file.readlines)
cursor.execute(sql)
cursor.close()
...
Run Code Online (Sandbox Code Playgroud)
在我进入其他任何东西之前,会在cursor.close()行上抛出错误,这对我来说没有任何意义......有人知道我做错了什么吗?在所有代码中只使用了一个线程.
我正在尝试使用在Mac OSX上运行的Ansible控制器创建一个新的MySQL数据库.当我第一次收到msg: the python mysqldb module is required错误消息时,我添加了一个安装MySQL-pythonwith 的任务pip.它已正确安装,但仍然我从Ansible要求安装时仍然收到错误.
我的最小剧本是:
- hosts: all
tasks:
- name: Ensure MySQL-python module is installed
pip:
name: MySQL-python
executalbe: /usr/local/Cellar/python/2.7.10_2/bin/pip
- name: Create test_db MySQL database
mysql_db:
name: test_db
state: present
Run Code Online (Sandbox Code Playgroud)
当我运行剧本时:
ansible-playbook -i "localhost," -c local mysql-test.yml
Run Code Online (Sandbox Code Playgroud)
我得到以下结果(changed第一次运行时的第一个任务):
TASK: [Ensure MySQL-python module is installed] **************************************
ok: [localhost]
TASK: [Create test_db MySQL database] *********************************************
failed: [localhost] => {"failed": true}
msg: the python mysqldb module is required …Run Code Online (Sandbox Code Playgroud) 我期待从Python中创建一个MySQL数据库.我可以找到有关如何连接到现有数据库的说明,但不能找到如何初始化新数据库的说明.
例如,当我运行该行时
import MySQLdb
db = MySQLdb.connect(host="localhost", user="john", passwd="megajonhy", db="jonhydb") (presumably because connecting will not create a database if it doesn't already exist, as i had hoped)
Run Code Online (Sandbox Code Playgroud)
关于如何使用Python连接MySQL数据库的第一行说明是什么?我收到了错误_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")
我如何初始化一个新的MySQL数据库来使用?
我有个问题 。我无法安装MysqlDB。
作业系统:CentOs6.8 x64 Python:2.7.6
pip2.7 install mysql-python
pip install mysql-python
Run Code Online (Sandbox Code Playgroud)
这是我的错误:
命令“ /usr/local/bin/python2.7 -u -c”导入setuptools,标记化;file ='/ tmp / pip-build-rgqmTQ / mysql-python / setup.py'; f = getattr(tokenize,'open',open)(file); code = f.read()。replace('\ r \ n','\ n'); f.close(); exec(compile(code,file,'exec')))“安装--record /tmp/pip-G4kWRa-record/install-record.txt- “单一版本外部管理的--compile”失败,错误代码为/ tmp / pip-build-rgqmTQ / mysql-python /