在项目中需要在一定条件满足时,保存一些数据到数据库中,并可根据条件查询。考虑到WinCC6.2以后采用的就是SQL Server2005数据库,所以直接利用该数据库即可,通过SQL Server Management Studio(SSMS)可以创建自己的数据库,并安要求创建好表。
一、数据库连接
在SQL Server Management Studio(SSMS)中创建名为evcp的数据库,再创建名为evcp的表,然后根据需要创建Columns,在本项目中创建了norder(流水号)、pileno(桩号)、cardno(卡号)、operno(员工号)、energy(电量)、cost(金额)、period(时长)、rate(费率)、pdate(日期)和ptime(时间)。
在本项目中采用ODBC的方式连接数据库,首先在控制面板中创建好数据源,配置好SQL Server驱动数据源,命名为evcs。
二、数据写入
要求在一个状态量值为1的时候完成数据库的保存,等数据保存完后将状态量清0。
1、先在全局脚本VBS项目模块中创建函数savedata,代码如下:
SubsavedataDimobjConnectionDimobjCommandDimobjRecordsetDimstrConnectionStringDimstrSQLDim norder,pileno,cardno,operno,energy,cost,period,rate,pdate,ptime
norder=HMIRuntime.Tags("norder").Read
pileno= HMIRuntime.Tags("pileno").Read
cardno=HMIRuntime.Tags("cardno").Read
operno= HMIRuntime.Tags("operno").Read
energy= HMIRuntime.Tags("energy").Read
cost= HMIRuntime.Tags("cost").Read
period= HMIRuntime.Tags("period").Readrate= HMIRuntime.Tags("rate").Read
pdate= HMIRuntime.Tags("pdate").Read
ptime= HMIRuntime.Tags("ptime").Read
strConnectionString= "Provider=MSDASQL;DSN=evcs;UID=;PWD=;"
Set objConnection = CreateObject("ADODB.Connection")
objConnection.ConnectionString=strConnectionString
objConnection.OpenSet objRecordset = CreateObject("ADODB.Record