python pyodbc文档翻译

pyodbc英文文档

https://code.google.com/archive/p/pyodbc/wikis/GettingStarted.wiki

连接数据库

直接连接到数据库并创建一个游标:
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()
使用DSN连接。因为DSN通常没有保存密码,所以你可能需要提供一个PWD密码:
cnxn = pyodbc.connect('DSN=test;PWD=password')
cursor = cnxn.cursor()
在连接的时候,这里有许多的选项,你可以详细查看连接函数(connect function)和连接字符串(ConnectionString)
选取一些数据
选择基本
所有的SQL语句都是通过cursor.execute函数执行的。如果语句返回多行,比如一个SELECT语句,你可以使用cursor fectch函数
(fetchone,fetchall,fetchmany)如果没有行,那么fetchone就会返回None,fetchall和fetchmany会返回空列表。
cursor.execute("select user_id, user_name from users") 
row = cursor.fetchone() 
if row: print row
行对象与元组类似,但是可以按名称使用列:
cursor.execute("select user_id, user_name from users") 
row = cursor.fetchone() 
print 'name:', row[1] 
# access by column index print 'name:', row.user_name 
# or access by name
当所有的行都被获取时fetchone函数返回None
while 1: 
    row = cursor.fetchone() 
if not row: 
    break print 'id:',row.user_id
fetchall函数以列表形式返回所有的剩余行。如果没有行,那么返回空列表(如果有许多行,那么将会占用大量的内存
未读取的行由数据库的驱动程序以紧凑的格式存储,常常从数据库以批量的形式发送。每次只读取你需要的数据将会节约很多内存)
cursor.execute("select user_id, user_name from users") 
rows = cursor.fetchall() 
for row in rows: 
    print row.user_id, row.user_name
如果你打算逐次处理多行,你可以把游标当成迭代器:
cursor.execute("select user_id, user_name from users"): 
    for row in cursor: 
        print row.user_id, row.user_name
或者可以简写为:
for row in cursor.execute("select user_id, user_name from users"):
     print row.user_id, row.user_name
许多SQL语句不能在一行内写完,你可以使用三引号的字符串:
cursor.execute(""" select user_id, user_name from users 
                   where last_logon < '2001-01-01' and bill_overdue = 'y' """)


参数:

ODBC支持使用问号作为SQL的占位符参数。您可以等SQL合格后再为?赋值:
cursor.execute(""" select user_id, user_name from users where last_logon < ? and bill_overdue = ? """, '2001-01-01', 'y')
单独向数据库传递值比直接在字符串中输入值要安全,因为这可以防止SQL遭受注入攻击。而且如果你要使用不同的值反复执行该语句时,这种方法更高效。
SQL只有一次处于preparedstatement,如果你在多个状态之间转换,那么就会多次处于preparedstatement
python DB API规定参数必须以一个序列传递,因此pyodbc也支持下面的句子:
cursor.execute(""" select user_id, user_name from users where last_logon < ? and bill_overdue = ? """, ['2001-01-01', 'y'])


cursor.execute("select count(*) as user_count from users where age > ?", 21) 
row = cursor.fetchone() 
print '%d users' % row.user_count


插入数据
把SQL语句和必要的参数传递给cursor.execute就可以插入数据
cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')") 
cnxn.commit()


cursor.execute("insert into products(id, name) values (?, ?)", 'pyodbc', 'awesome library') 
cnxn.commit()


注意,要有cnxn.commit(),必须使用commit,否则数据会丢失。当连接中断的时候,所有未决定的变化(pending changes)都会撤回(roll back)
这使得错误修复更简单,但是你一定记得调用commit


更新与删除

更新与删除同样是传递SQL语句给execute进行。如果你想知道在刷新删除后有多少条记录受影响,你可以使用cursor.rowcount的值
cursor.execute("delete from products where id <> ?", 'pyodbc') 
print cursor.rowcount, 'products deleted' 
cnxn.commit()
执行后返回cursor,你有时也会看见这样的代码:
deleted = cursor.execute("delete from products where id <> 'pyodbc'").rowcount 
cnxn.commit()
注意这个cnxn.commit(),必须使用commit,否则数据会丢失。当连接中断的时候,所有未决定的变化(pending changes)都会撤回(roll back)
这使得错误修复更简单,但是你一定记得调用commit

提示与技巧

因为单引号在SQL语句中有效,你可以用双引号中书写SQL语句
deleted = cursor.execute("delete from products where id <> 'pyodbc'").rowcount
如果你使用三引号,你也可以这样写:
deleted = cursor.execute(""" delete from products where id <> 'pyodbc' """).rowcount
有些数据库,比如SQL Server,计算时不产生列名,这时,你可以通过列索引访问列。你也可以使用“AS”关键字为列命名。
row = cursor.execute("select count(*) as user_count from users").fetchone() 
print '%s users' % row.user_count
如果你需要的值只有一个,你可以用fetch取得该行并抽取第一列。
count = cursor.execute("select count(*) from users").fetchone()[0] print '%s users' % count
若第一列为空时该语句无效。这时的fetchone()返回None,并会得到一个错误:NoneTypebu 不支持索引。
如果存在一个默认值,你可以使用ISNULL或者coalesce在SQL语句中直接把NULL转化为默认值:
maxid = cursor.execute("select coalesce(max(id), 0) from users").fetchone()[0]

这个例子中,如果max(id)返回NULL,coalesce(max(id), 0)将会把选定的值转化为0.


参考文章:

pyodbc 连接sql server   http://my.oschina.net/acemumu/blog/94266?fromerr=IfETTFMj
python 连接数据库:
http://c.360webcache.com/c?m=3945102cf1c4410a5126b0970fbb27c6&q=PYODBC&u=http%3A%2F%2Fblog.sina.com.cn%2Fs%2Fblog_7ca42bff010188yv.html


你可能感兴趣的:(python pyodbc文档翻译)