完成vb下将excel的表导入sql

忙了两天,找书,上网,查了一些资料总算吧这个问题解决了。对于像编程开发一类的工作,有时看书没太大的帮助,以为实践性比较强,还真的不如上网baidu或google一下来的快。前两天找的那篇文章其实没有利用上,倒是连到CSDN上的一个帖子给了直接方法。帖子表述如下:
******************************************************************
'引用ADO(Microsoft   ActiveX   Data   Objects   2.X   Library) 
  Private   Sub   Command1_Click() 
          On   Error   GoTo   err 
          Dim   cn   As   New   ADODB.Connection 
          '具体的数据库连接请自己改过来 
          cn.ConnectionString   =   "Provider=SQLOLEDB.1;Persist   Security   Info=False;User   ID=sa;Password=123;Initial   Catalog=dataBase001;Data   Source=mySERVICE" 
          cn.CursorLocation   =   adUseClient 
          cn.Open         
          cn.Execute   "select   *   into   NewTable   from   OpenRowSet('microsoft.jet.oledb.4.0','Excel   8.0;HDR=Yes;database=c:/Test.xls;','select   *   from   [Sheet1$]')" 
          cn.Close 
          Set   cn=Nothing 
          Exit   Sub 
  err: 
          MsgBox   err.Description 
  End   Sub
********************************************************************
由于刚接触数据库,知道这用的是ADO的方法,但是不知道他那引用ADO是什么意思,跑起代码总是第一个声明就错了。后来才知道要在工程->引用里把Microsoft ActiveX Data Library 2.x 选上。
现在目标已经实现,想把其中的几个点记录一下.
1.与sql的连接
这是一个最头大的问题,个人觉得最重要的就是把身份验证设为“混合模式”,用“windows模式”安全但是对编程开发很不便。在想方便就是选择“空密码”;
2.connectionstring
连接字符串各个参数的顺序可以互换,Initial   Catalog指数据库的名称,Data   Source指数据库服务器的地址。
3.sql语句中变量作为参数
变量还放在原参数的位置,但要在其两侧放上&,在加两个双引号,比如下句:
select   *   into   NewTable   from
现在用变量table代替NewTable
select   *   into   " & table & "  from

最后实现的代码如下:
Private Sub Command1_Click()
On Error GoTo err
          Dim cn     As New ADODB.Connection
         
          database = Text3.Text
          table = Text2.Text
          'cn.ConnectionString = "Provider=SQLOLEDB.1;Password=;Persist Security Info=false;User ID=sa;Initial Catalog=" & database & ";Data Source=(local)"
          cn.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=false;User ID=sa;Password=;Initial Catalog=" & database & ";Data Source=(local)"
          cn.CursorLocation = adUseClient
          cn.Open
         
          'cn.Execute "select   *   into   NewTable   from   OpenRowSet('microsoft.jet.oledb.4.0','Excel 8.0;HDR=yes;database=e:/test.xls;','select   *   from   [Sheet1$]')"
          cn.Execute "select   *   into   " & table & "  from   OpenRowSet('microsoft.jet.oledb.4.0','Excel 8.0;HDR=yes;database=" & filenamefet & ";','select   *   from   [Sheet1$]')"
          cn.Close
          Set cn = Nothing
          MsgBox "ok!"
          Exit Sub
err:
          MsgBox err.Description
End Sub

Private Sub Command2_Click()
    CommonDialog1.Filter = "EXCEL文件(*.xls)|*.xls"
    CommonDialog1.ShowOpen
    filenamefet = CommonDialog1.FileName
    Text1.Text = filenamefet
End Sub
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值