[英]error of creating tables on SQL server 2008 R2 from python3.2 and pyodbc on win7
I am trying to access SQL server 2008 R2 from Eclipse pydev ( python 3.2 ) on win7 . 我正在尝试在win7上从Eclipse pydev(python 3.2)访问SQL Server 2008 R2。
I need to create a table on database. 我需要在数据库上创建一个表。
The code can be run well. 该代码可以很好地运行。 But, I cannot create tables in the database.
但是,我无法在数据库中创建表。 If I print the sql string and run the query from SQL server management studio, no problems.
如果我打印sql字符串并从SQL Server Management Studio运行查询,则没有问题。
import pyodbc
sql_strc = " IF OBJECT_ID(\'[my_db].[dbo].[my_table]\') IS NOT NULL \n"
sql_strc1 = " DROP TABLE [my_db].[dbo].[my_table] \n"
sql_stra = " CREATE TABLE [my_db].[dbo].[my_table] \n"
sql_stra1 = "(\n"
sql_stra1a = " person_id INT NOT NULL PRIMARY KEY, \n"
sql_stra1b = " value float NULL, \n"
sql_stra1r = "); \n"
sql_str_create_table = sql_strc + sql_strc1 + sql_stra + sql_stra1 + sql_stra1a + sql_stra1b + sql_stra1r
# create table
sql_str_connect_db = "DRIVER={SQL server};SERVER={my_db};DATABASE={my_table};UID=my_id; PWD=my_password"
cnxn = pyodbc.connect(sql_str_connect_db)
cursor = cnxn.cursor()
cursor.execute( sql_str_create_table)
Any help would be appreciated. 任何帮助,将不胜感激。
Thanks 谢谢
Autocommit is off by default , add the following to commit your change: 默认情况下 , 自动提交是关闭的 ,添加以下内容以提交更改:
cnxn.commit()
Some unsolicited advice for making your code more readable: 一些不请自来的建议,以使您的代码更具可读性:
"""
) syntax when defining multiline strings. Newline characters are preserved and don't need to be explicitly added. """
)语法,保留了换行符,无需显式添加。 With these changes, your final code looks something like: 经过这些更改,您的最终代码如下所示:
import pyodbc
sql = """
IF OBJECT_ID('[my_db].[dbo].[my_table]') IS NOT NULL
DROP TABLE [my_db].[dbo].[my_table]
CREATE TABLE [my_db].[dbo].[my_table]
(
person_id INT NOT NULL PRIMARY KEY,
value FLOAT NULL
)
"""
cnxn = pyodbc.connect(driver='{SQL Server}', server='server_name',
database='database_name', uid='uid', pwd='pwd')
cursor = cnxn.cursor()
# create table
cursor = cursor.execute(sql)
cnxn.commit()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.