.mdb.access数据库VBA-利用SQL语句创建数据库和数据表 |
| 时间:2025-01-20 08:51:19 来源: 作者: |
利用SQL语句创建数据库和数据表首先引用:microsoft activeX data objects 2.X library 和 microsoft ado ext.2.x for ddl and security”O8E检测VBA 代码:O8E检测VBA public sub1_3()O8E检测VBA dim mycat as new adox.catalog ‘定义ADOX的Catalog对象变量O8E检测VBA Dim mycmd as new adodb.command ‘定义Command对象变量O8E检测VBA dim mydata as string ‘定义数据库名称变量O8E检测VBA dim mytable as string ‘定义数据表名称变量O8E检测VBA dim SQL as stringO8E检测VBA O8E检测VBA ‘设置要创建的数据库名称(包括完整路径)O8E检测VBA mydata=thisworkbook.path & “\学生成绩管理.mdb”O8E检测VBA O8E检测VBA ‘设置要创建的数据表名称O8E检测VBA mytable=”期末成绩”O8E检测VBA O8E检测VBA ‘删除已经存在的数据库文件O8E检测VBA on error resume nextO8E检测VBA kill mydataO8E检测VBA on error goto 0O8E检测VBA O8E检测VBA ‘创建数据库文件O8E检测VBA mycat.create “provider=microsoft.jet.oledb.4.0;Data source=” & mydataO8E检测VBA O8E检测VBA ‘设置数据库连接O8E检测VBA set mycmd.activeconnection=mycat.activeconnectionO8E检测VBA O8E检测VBA ‘设置创建数据表的SQL语句O8E检测VBA SQL = "CREATE TABLE " & myTable _O8E检测VBA & "(学号 text(10),姓名 text(6),性别 text(1),班级 text(10)," _O8E检测VBA & "数学 Single,语文 Single,物理 Single,化学 Single," _O8E检测VBA & "英语 Single,总分 Single)"O8E检测VBA ‘利用execute方法创建数据表O8E检测VBA with mycmdO8E检测VBA .commandtext=sqlO8E检测VBA .execute, , adcmdtextO8E检测VBA end withO8E检测VBA O8E检测VBA ‘释放变量O8E检测VBA set mycat=nothingO8E检测VBA set mycmd=nothingO8E检测VBA ‘弹出信息O8E检测VBA msgbox “创建数据库成功!” & vbcrlf & “数据库文件名为:” & mydata & vbcrlf & “数据表名称为:” & mytable & vbcrlf & “保存位置:” & thisworkbook.path,vbinformation,”创建数据库”O8E检测VBA end subO8E检测VBA
注:有两种方法来创建数据表: ·利用ADODB.Command对象的commandtext属性和execute方法:O8E检测VBA dim mycmd as new adodb.commandO8E检测VBA set mycmd.activeconnection=mycat.activeconnectionO8E检测VBA with mycmdO8E检测VBA .commandtext=SQLO8E检测VBA .execute, , adcmdtextO8E检测VBA end withO8E检测VBA ·利用ADODB.Connection对象的execute方法来生成几个记录集O8E检测VBA Dim cnn as new adodb.connectionO8E检测VBA dim rs as new adodb.recordsetO8E检测VBA set cnn=mycat.activeconnectionO8E检测VBA set rs=cnn.execute(sql)O8E检测VBA |
|
|
|