cad和数据库连接,是个很有用的问题.最近实现了用visual lisp对access数据库的操作,包括配置数据库,读/写数据.
先看数据库:
名称:mc-sample.mdb,表名称:circle.共id,x,y,z,r四个字段.其中id为序号,x,y,z为圆心坐标,r为圆半径.
欲实现:从该数据库中取出所有记录,在cad中以相应参数画圆.
把文件mc-sample.mdb拷到autocad2004的支持文件夹中(例如,我的是c:/program files/auotcad2004/support/).然后新建rw.lsp,其代码如下:
(vl-load-com)
(defun c:loadcircle(/ dbfile conn connstring sql rs resultlist count i pn)
(setq dbfile (findfile "mc-sample.mdb")) ;设置数据库名称及路径
(Setq conn(vlax-create-object "ADODB.Connection")) ;引用ADO控件
(setq connstring (strcat "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" dbfile)) ;设置数据库连接字符串
(vlax-invoke-method conn "open" connstring "" "" -1) ;打开数据库连接
(setq sql "select [id],[x],[y],[z],
from [circle] order by [id]") ;设置查询SQL
(setq rs (vlax-invoke-method conn "Execute" sql nil -1)) ;执行数据库查询
(if (/= (vlax-get-property rs "EOF") :vlax-true) ;判断有无数据
(progn
(setq resultlist (vlax-safearray->list (vlax-variant-value (vlax-invoke-method rs "GetRows" -1))));将返回值变成列表
(setq count(vl-list-length (car resultlist)));查询列表长度,即记录数
(setq i 0)
(repeat count
(setq x (vlax-variant-value(nth i(cadr resultlist)));取X坐标
y (vlax-variant-value(nth i(caddr resultlist)));取Y坐标
z (vlax-variant-value(nth i(cadddr resultlist)));取Z坐标
r (vlax-variant-value(nth i(nth 4 resultlist)));取R长度
i (1+ i)
)
;;(princ (strcat "/n" (rtos x) "," (rtos y) "," (rtos z) "," (rtos r))) ;列出记录内容
(setq pn (list x y z)) ; 将XYZ组合成点坐标
(command "_circle" pn r ) ;画圆
)
)
)
(setq sql "insert into [circle] ([id],[x],[y],[z],[r]) values(12,1,1,0,6)") ;插入记录
(setq rs (vlax-invoke-method conn "Execute" sql nil -1)) ;执行数据库查询
(vlax-release-object rs);释放记录集
(vlax-invoke-method conn "close");关闭数据库连接
(vlax-release-object conn);释放数据库连接
)
如此,实现了lisp-access操作,下一步需要解决的,是用lisp操作sql server,毕竟access作为数据库,还是太简单了啊.