我在创建数据库和表时遇到了麻烦.需要在Python脚本中创建数据库.
#connect method has 4 parameters:
#localhost (where mysql db is located),
#database user name,
#account password,
#database name
db1 = MS.connect(host="localhost",user="root",passwd="****",db="test")
Run Code Online (Sandbox Code Playgroud)
回报
_mysql_exceptions.OperationalError: (1049, "Unknown database 'test'")
Run Code Online (Sandbox Code Playgroud)
很明显,首先需要创建db1,但是如何?我在connect()语句之前尝试过CREATE但是出错了.
创建数据库后,如何创建表?谢谢,汤姆
这是语法,这至少是第一次使用.第二次自然返回db已经存在.现在来弄清楚如何正确使用drop命令.
db = MS.connect(host="localhost",user="root",passwd="****")
db1 = db.cursor()
db1.execute('CREATE DATABASE test1')
Run Code Online (Sandbox Code Playgroud)
所以第一次这很好用.第二次通过提供警告"db已存在".怎么处理这个?以下是我认为它应该如何工作,但事实并非如此.或者它应该是if语句,寻找它是否已经存在,不填充?
import warnings
warnings.filterwarnings("ignore", "test1")
Run Code Online (Sandbox Code Playgroud) 我在本网站上已经以各种方式看到了这个问题,但它们都没有完全解决我的问题.
我有一个带有单引号的sql语句,并且在使用它进行数据库查询之前尝试使用推荐的做法.所以声明就像
val2="abc 'dostuff'"
sql="INSERT INTO TABLE_A(COL_A,COL_B) VALUES(%s,'%s')" %(val1, val2)
a_cursor.execute(sql)
Run Code Online (Sandbox Code Playgroud)
但是,当我运行这个时,我得到..
ProgrammingError: (1064,"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'dostuff'.
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?非常感谢Nupur
我正在尝试安装MySQLdb扩展,但我得到这个错误,任何想法可能是什么原因?可能是有权限的东西?我正在使用Mac OX Lion ....
这是错误的一部分.Django安装正常,但我需要安装此扩展.谢谢你的帮助.
ppp-071ca:MySQL-python-1.2.4b4 miguel_e$ sudo python setup.py install
running install
running bdist_egg
running egg_info
writing MySQL_python.egg-info/PKG-INFO
writing top-level names to MySQL_python.egg-info/top_level.txt
writing dependency_links to MySQL_python.egg-info/dependency_links.txt
writing MySQL_python.egg-info/PKG-INFO
writing top-level names to MySQL_python.egg-info/top_level.txt
writing dependency_links to MySQL_python.egg-info/dependency_links.txt
reading manifest file 'MySQL_python.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'MySQL_python.egg-info/SOURCES.txt'
installing library code to build/bdist.macosx-10.7-intel/egg
running install_lib
running build_py
copying MySQLdb/release.py -> build/lib.macosx-10.7-intel-2.7/MySQLdb
running build_ext
building '_mysql' extension
llvm-gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-
strict-aliasing -fwrapv …Run Code Online (Sandbox Code Playgroud) 我们尝试将包含多个插入语句的SQL文件作为单个查询运行,但是rollback当任何语句包含错误时,它似乎都失败了.
MySQLd配置:
sql_mode = STRICT_ALL_TABLES
default-storage-engine = innodb
Run Code Online (Sandbox Code Playgroud)
Python代码:
from contextlib import closing
import MySQLdb
database_connection = MySQLdb.connect(host="127.0.0.1", user="root")
with closing(database_connection.cursor()) as cursor:
database_connection.begin()
cursor.execute('DROP DATABASE IF EXISTS db_name')
cursor.execute('CREATE DATABASE db_name')
cursor.execute('USE db_name')
cursor.execute('CREATE TABLE table_name(first_field INTEGER)')
with closing(database_connection.cursor()) as cursor:
try:
database_connection.begin()
cursor.execute('USE db_name')
cursor.execute('INSERT INTO table_name VALUES (1)')
cursor.execute('INSERT INTO table_name VALUES ("non-integer value")')
database_connection.commit()
except Exception as error:
print("Exception thrown: {0}".format(error))
database_connection.rollback()
print("Rolled back")
with closing(database_connection.cursor()) as cursor:
try:
database_connection.begin()
cursor.execute('USE db_name')
cursor.execute('INSERT INTO …Run Code Online (Sandbox Code Playgroud) 在Mountain Lion更新之前,它就像一个魅力.
更新后,它被破坏,我无法再次获得环境.
有人知道如何解决这个问题吗?
错误以粗体显示,如下所示.
fedorius@this:~$ pip install mysql-python
Downloading/unpacking mysql-python
Downloading MySQL-python-1.2.5.zip (108kB): 108kB downloaded
Running setup.py (path:/private/var/folders/21/zjvwzn891jnf4rnp526y13200000gn/T/pip_build_fedorius/mysql-python/setup.py) egg_info for package mysql-python
Installing collected packages: mysql-python
Running setup.py install for mysql-python
building '_mysql' extension
cc -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -pipe -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/local/mysql/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.9-intel-2.7/_mysql.o -Os -g -fno-strict-aliasing -arch x86_64
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: …Run Code Online (Sandbox Code Playgroud) 以下逻辑适用于mysqldb模块(请参阅python mysqldb一个连接的多个游标),但我在cursor2.execute(sql)上使用mysql.connector收到以下错误
"发现未读结果."
我意识到我可以使用连接来组合这两个简单的sql语句,并避免需要第二个游标,但我的真实世界的例子更复杂,需要第二个sql语句.
假设我需要执行2个单独的sql语句(1个用于循环,1个用于循环),如何使用mysql.connector模块完成?
import datetime
import mysql.connector
db = mysql.connector.connect(user='alan', password='please', host='machine1', database='mydb')
cursor1 = db.cursor()
cursor2 = db.cursor()
sql = """
SELECT userid,
username,
date
FROM user
WHERE date BETWEEN %s AND %s
"""
start_date = datetime.date(1999, 1, 1)
end_date = datetime.date(2014, 12, 31)
cursor1.execute(sql, (start_date, end_date))
for (userid, username, date) in cursor1:
sql = """
select count(*)
from request
where assigned = '%s'
""" % (userid)
cursor2.execute(sql)
requestcount = cursor2.fetchone()[0]
print userid, requestcount
cursor2.close() …Run Code Online (Sandbox Code Playgroud) 我有这个代码:
cursor = conn.cursor()
cursor.execute(("insert into new_files (videos_id, filename, "
"is_processing) values (%s,%s,1)"), (id, filename))
logging.warn("%d", cursor.rowcount)
if (cursor.rowcount == 1):
logging.info("inserted values %d, %s", id, filename)
else:
logging.warn("failed to insert values %d, %s", id, filename)
cursor.close()
Run Code Online (Sandbox Code Playgroud)
有趣的是,cursor.rowcount是总是一个,即使我更新了我的数据库,以使videos_id一个独特的密钥.也就是说,插入失败,因为在我的测试videos_id中会出现同样的情况(当我检查数据库时,没有插入任何内容).但无论出于何种原因,rowcount它总是1 - 即使logging.warn我已经吐了rowcount1.
所以,问题是:如果插入正常,
我可以使用rowcount吗?如果是这样,我(大概)做错了什么?否则,我如何检查插入是否正常?
假设,我有一个修改声明:
cursor = conn.cursor()
# some code
affected_rows1 = cursor.execute(update_statement1, params1)
# some code
conn.commit()
cursor.close()
Run Code Online (Sandbox Code Playgroud)
我是否应该使用a包装代码块try ... except并在引发异常时显式回滚事务,以及应该捕获哪些MySQLdb异常?StandardError在这种情况下我常常捕获任何内容,但现在我犹豫不决,代码块甚至需要显式回滚.
以下示例稍微困难一点,我知道如果第一个更新语句成功,它确实需要显式回滚.在这种情况下,我应该抓住哪些例外:
cursor = conn.cursor()
# some code
affected_rows1 = cursor.execute(update_statement1, params1)
# some code
affected_rows2 = cursor.execute(update_statement2, params2)
#some code
conn.commit()
cursor.close()
Run Code Online (Sandbox Code Playgroud) 我正在使用MySQLdb模块从python使用MySQL 5.0.
考虑一个简单的函数来加载和返回整个数据库表的内容:
def load_items(connection):
cursor = connection.cursor()
cursor.execute("SELECT * FROM MyTable")
return cursor.fetchall()
Run Code Online (Sandbox Code Playgroud)
此查询旨在成为一个简单的数据加载,并且除了该单个SELECT语句之外没有任何事务行为.
在运行此查询之后,可能需要一段时间再次使用相同的连接来执行其他任务,尽管其他连接仍然可以同时在数据库上运行.
我应该在通话connection.commit()后尽快cursor.execute(...)打电话,以确保操作未在连接上留下未完成的交易吗?
我有一个MSQL数据库,我需要遍历一个表并在满足WHERE子句后执行操作.然后一旦到达桌子的尽头,返回顶部并重新开始.
目前我有
cursor = database.cursor()
cursor.execute("SELECT user_id FROM round WHERE state == -1 AND state = 2")
round_id = cursor.fetchone()
if round != 5
...do stuff
Run Code Online (Sandbox Code Playgroud)
在循环中但这显然只是循环第一个条目.我想你需要使用for in函数来读取表格,但我不确定如何使用mysqldb完成这个操作?