1、连接数据库 1 ^( U. l1 R! {) J& a4 p) P m * h5 a, p. V! R* H8 O1)直接连接数据库和创建一个游标(cursor)4 j3 Q3 x3 J$ H
1 cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=meWD=pass'). Z4 }1 J" I3 X; {$ m" a/ l7 N! ~
2 cursor = cnxn.cursor()4 V, w! h0 e; C. D' p8 I$ g
4 x0 U f# ~/ a! b( V2)使用DSN连接。通常DSN连接并不需要密码,还是需要提供一个PSW的关键字。% J' b* ?3 Z8 w; g9 q
1 cnxn = pyodbc.connect('DSN=testWD=password') 9 B* Y' d# D4 n' j% H( z) m2 cursor = cnxn.cursor() / ?( ^! [: W$ d ; v8 I' z/ D5 e8 Y8 S; @* q h! Y关于连接函数还有更多的选项,可以在pyodbc文档中的 connect funtion 和 ConnectionStrings查看更多的细节- `/ r4 S5 d' }' l" A9 c
/ E, T- @; l/ t/ S
2、数据查询(SQL语句为 select ...from..where) 1 f( V* f- G- T5 f& D9 B# G* S% n, y- ^4 A. k$ C8 T+ v4 U
1)所有的SQL语句都用cursor.execute函数运行。如果语句返回行,比如一个查询语句返回的行,你可以通过游标的fetch函数来获取数据,这些函数有(fetchone,fetchall,fetchmany).如果返回空行,fetchone函数将返回None,而fetchall和fetchmany将返回一个空列。 7 {; g" y5 N: T/ W- Y5 y9 g1 cursor.execute("select user_id, user_name from users")/ Z) a% A# g, c8 ?7 x
2 row = cursor.fetchone()& Z8 o' V2 m/ F/ C9 d1 a) W" E4 s& ^/ }+ q
3 if row: * t: R; F. l$ [/ x$ _0 ~# K4 print row ; K, e- @; K9 a) N& `; ~) g$ x( L* \1 Y) O- Q6 q% R s
2)Row这个类,类似于一个元组,但是他们也可以通过字段名进行访问。* o: s$ A- |; X9 R$ o
1 cursor.execute("select user_id, user_name from users")2 M. e! y( s/ ]& b( z
2 row = cursor.fetchone() _: Z7 x) `5 Z, b V+ E3 print 'name:', row[1] # access by column index* Q1 o4 R' d, S' B# W
4 print 'name:', row.user_name # or access by name # N7 r _4 ?! G3 M" w$ n / [. \ H2 h) J3)如果所有的行都被检索完,那么fetchone将返回None.3 X) m; A5 J: F
1 while 1: ( Y- }4 V- V- `% Q/ K# B( T4 ~2 row = cursor.fetchone()4 t" p& z9 _, P; _; _2 v( [
3 if not row:8 a# h! n. H: U$ q6 H0 ?
4 break 3 F4 | g& D' R. L$ W- v7 T5 print 'id:', row.user_id 7 L/ T1 w) M; N1 P; R( ^- R! h4 K' m4 G( f. l( D( L
4)使用fetchall函数时,将返回所有剩下的行,如果是空行,那么将返回一个空列。(如果有很多行,这样做的话将会占用很多内存。未读取的行将会被压缩存放在数据库引擎中,然后由数据库服务器分批发送。一次只读取你需要的行,将会大大节省内存空间) ! x: ~; g# Z' Y9 p$ L8 d1 cursor.execute("select user_id, user_name from users")( r: {8 S. F( d t7 T
2 rows = cursor.fetchall() ) H4 `/ b5 @* E, |! m3 for row in rows: 2 t% p9 ~. F7 M- J3 g4 print row.user_id, row.user_name * O: j h- O6 a% s) c: y" G! G" C, g& g7 G, F# L
5)如果你打算一次读完所有数据,那么你可以使用cursor本身。0 d, y% q6 Q6 L
1 cursor.execute("select user_id, user_name from users"): + z' ^/ f! _* |$ H8 r2 for row in cursor:; n% L3 _+ f% C
3 print row.user_id, row.user_name/ s, ^( C# w- f A% t
. o4 v! |" s. j4 D6)由于cursor.execute返回一个cursor,所以你可以把上面的语句简化成: 8 i5 w. }$ \0 ~1 for row in cursor.execute("select user_id, user_name from users"):2 K+ b( r h$ P' k; t! N/ e
2 print row.user_id, row.user_name' j. V% R+ @* o
1 p5 L: }5 e5 |0 |7)有很多SQL语句用单行来写并不是很方便,所以你也可以使用三引号的字符串来写:- ~- h, ?- {& ^# p- o1 u
1 cursor.execute(""" ! x4 N) ?% Q7 L4 v6 v2 K2 select user_id, user_name 1 l" J; [ _* l$ x3 from users- _# U6 i6 F9 Q
4 where last_logon < '2001-01-01': M4 G. A/ U: r3 V6 v* C4 D- g9 C
5 and bill_overdue = 'y'( o7 @4 ~% _( `0 U
6 """) 4 v7 z3 X1 b2 U# F/ {7 b9 N/ Y% i+ v& {5 |! ]: I
3、参数. N. `; T* D3 L( C' b
' r' ^5 P3 @5 X8 c |! \1)ODBC支持在SQL语句中使用一个问号来作为参数。你可以在SQL语句后面加上值,用来传递给SQL语句中的问号。 3 A( ^! X6 _9 v; S6 N( P- z) h1 cursor.execute(""" ( E( T4 c5 E" x0 q% u- l" x0 T2 select user_id, user_name . }3 j1 A9 x; n3 from users . Y" P: `8 x* K0 d' h4 where last_logon < ?# o4 R2 |: _" _9 }# T
5 and bill_overdue = ?/ E9 h. O, J, x% E8 k4 k0 L
6 """, '2001-01-01', 'y') $ Q( O& H" y& U( a D 6 \5 v) _& A6 y8 Q. N1 O这样做比直接把值写在SQL语句中更加安全,这是因为每个参数传递给数据库都是单独进行的。如果你使用不同的参数而运行同样的SQL语句,这样做也更加效率。6 O; ~9 T. B# b5 s8 y* |* z* q1 `
9 f4 O; n* n: _) i. w, n
3)python DB API明确说明多参数时可以使用一个序列来传递。pyodbc同样支持: 2 v0 i6 N( q4 g& _+ A( D5 ~1 cursor.execute(""" . E: V9 @, e5 R6 U; x( A( O5 z2 select user_id, user_name " s# X2 E9 _9 |3 S; Q1 @0 ~* e3 from users$ n; f# d. P8 e( H) m1 A
4 where last_logon < ? 1 V9 x7 I) K+ I! x, j$ ]' n5 and bill_overdue = ?2 j7 s. \6 s9 r: j% v$ y0 x& R
6 """, ['2001-01-01', 'y'])7 c* x' F+ O5 x, h: f, F, S
0 d2 o! ]) p/ t! O- h
1 cursor.execute("select count(*) as user_count from users where age > ?", 21) 8 g2 {( ?, @# }( F' z7 y2 row = cursor.fetchone() : K/ ?- Q5 o" z3 print '%d users' % row.user_count 4 \6 g+ @6 L9 z; }1 B* K4 r3 ]* n0 `: y- L) }* P