import win32com.client
conn = win32com.client.Dispatch(r'ADODB.Connection')
DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0DATA SOURCE=C:/MyDB.mdb'
conn.Open(DSN)
Python *** 作Access数据库步骤之2、打开一个记录集
rs = win32com.client.Dispatch(r'ADODB.Recordset')
rs_name = 'MyRecordset'#表名
rs.Open('[' + rs_name + ']', conn, 1, 3)
Python *** 作Access数据库步骤之3、对记录集 *** 作
rs.AddNew()
rs.Fields.Item(1).Value = 'data'
rs.Update()
Python *** 作Access数据库步骤之4、用SQL来插入或更新数据
conn = win32com.client.Dispatch(r'ADODB.Connection')
DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0DATA SOURCE=C:/MyDB.mdb'
sql_statement = "Insert INTO [Table_Name] ([Field_1],
[Field_2]) VALUES ('data1', 'data2')"
conn.Open(DSN)
conn.Execute(sql_statement)
conn.Close()
Python *** 作Access数据库步骤之5、遍历记录
rs.MoveFirst()
count = 0
while 1:
if rs.EOF:
break
else:
countcount = count + 1
rs.MoveNext()
注意:如果一个记录是空的,那么将指针移动到第一个记录将导致一个错误,因为此时recordcount是无效的。解决的方法是:打开一个记录集之前,先将Cursorlocation设置为3,然后再打开记录集,此时recordcount将是有效的。例如:
rs.Cursorlocation = 3 # don't use parenthesis here
rs.Open('Select * FROM [Table_Name]', conn) # be sure conn is open
rs.RecordCount # no parenthesis here either
import pyodbcdbfile="db2.mdb"
try:
conn=pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)}PWD=thepwdDBQ='+dbfile)
cur=conn.cursor()
cur.execute("select * from standard")
print cur.fetchone()
print dir(cur)
except pyodbc.Error,e:
print e[1]
except pyodbc.ProgrammingError,e:
print e[1]
#!/usr/bin/env python# -*- conding: utf-8 -*-
import pypyodbc
if __name__=="__main__":
str = 'Driver={Microsoft Access Driver (*.mdb)}DBQ=E:\\123.mdb'
conn = pypyodbc.win_connect_mdb(str)
#conn = pypyodbc.connect(str)
cur = conn.cursor()
cur.execute("SELECT * FROM catalog")
for row in cur.fetchall():
for field in row:
print field,
print ''
conn.commit()
cur.close()
conn.close()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)