search
HomeDatabaseMysql TutorialExcel数据导入到Access,Sql Server中示例代码

副标题 将Excel中的 数据 导入 到Access中,前提是在Access中的表已经建好。 dim conn dim conn2 set conn=CreateObject("ADODB.Connection") conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=;Data Source=c:\book1.mdb" set

将Excel中的数据导入到Access中,前提是在Access中的表已经建好。

dim conn
dim conn2
set conn=CreateObject("ADODB.Connection")
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=;Data Source=c:\book1.mdb"

set conn2=CreateObject("ADODB.Connection")
conn2.Open "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=;Extended properties=Excel 5.0;Data Source=c:\book1.xls"


sql = "SELECT * FROM [Sheet1$]"
set rs = conn2.execute(sql)
while not rs.eof
 sql = "insert into xxx([a],[b],[c],[d]) values('"& fixsql(rs(0)) &"','"& fixsql(rs(1)) &"','"& fixsql(rs(2)) &"','"& fixsql(rs(3)) &"')"
 conn.execute(sql)
 rs.movenext
wend

conn.close
set conn = nothing
conn2.close
set conn2 = nothing

function fixsql(str)
 dim newstr
 newstr = str
 if isnull(newstr) then
  newstr = ""
 else
  newstr = replace(newstr,"'","''")
 end if
 fixsql = newstr
end function

导入到Sql Server数据库中时,如果Excel文件和数据库不在同一台服务器上时,请参考上面的代码。在同一机器上可以参考下面代码(不需要先把表建表,程序会自己动建表,用Excel中的第一行数据做为表的字段名):

dim conn
set conn=CreateObject("ADODB.Connection")
conn.Open ("driver={SQL Server};server=localhost;uid=sa;pwd=sa;database=hwtemp;")
sql = "SELECT * into newtable FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0','Data Source=""c:\book1.xls"";User ID=Admin;Password=;Extended properties=Excel 5.0')...[Sheet1$] "
conn.execute(sql)

conn.close
set conn = nothing

选择自 sxycgxj 的 Blog

 

本文作者:


  该错误产生的原因是由于SQL Server使用了"仅 Windows"的身份验证方式,因此用户无法使用SQL Server的登录帐户(如 sa )进行连接。解决方法如下所示:
1、在服务器端使用企业管理器,并且选择"使用 Windows 身份验证"连接上 SQL Server;

  2、展开"SQL Server组",鼠标右键点击SQL Server服务器的名称,选择"属性",再选择"安全性"选项卡;

  3、在"身份验证"下,选择"SQL Server和 Windows ";

  4、重新启动SQL Server服务。

  在以上解决方法中,如果在第1步中使用"使用 Windows 身份验证"连接 SQL Server 失败,那就通过修改注册表来解决此问题:

  1、点击"开始" "运行",输入regedit,回车进入注册表编辑器;

  2、依次展开注册表项,浏览到以下注册表:[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\MSSQLServer];

  3、在屏幕右方找到名称"LoginMode",双击编辑双字节值;

  4、将原值从1改为2,点击"确定";

  5、关闭注册表编辑器;

  6、重新启动SQL Server服务。

  此时,用户可以成功地使用sa在企业管理器中新建SQL Server注册,但是仍然无法使用Windows身份验证模式来连接SQL Server。这是因为在 SQL Server 中有两个缺省的登陆户:

BUILTIN\Administrators
\Administrator 被删除。

  要恢复这两个帐户,可以使用以下的方法:

  1、打开企业管理器,展开服务器组,然后展开服务器;

  2、展开"安全性",右击"登录",然后单击"新建登录";

  3、在"名称"框中,输入 BUILTIN\Administrators;

  4、在"服务器角色"选项卡中,选择"System Administrators" ;

  5、点击"确定"退出;

  6、使用同样方法添加 \Administrator 登录。

  说明:

  以下注册表键:

  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\MSSQLServer\LoginMode的值决定了SQL Server将采取何种身份验证模式。

  1、表示使用"Windows 身份验证"模式;

  2、表示使用混合模式(Windows 身份验证和 SQL Server 身份验证)。

  三、提示连接超时


(图6)

如果遇到第三个错误,一般而言表示客户端已经找到了这台服务器,并且可以进行连接,不过是由于连接的时间大于允许的时间而导致出错。这种情况比较少见,一般发生在当用户在Internet上运行企业管理器来注册另外一台同样在Internet上的服务器,并且是慢速连接时,有可能会导致以上的超时错误。有些情况下,由于局域网的网络问题,也会导致这样的错误。

  要解决这样的错误,可以修改客户端的连接超时设置。默认情况下,通过企业管理器注册另外一台SQL Server的超时设置是 4 秒,而查询分析器是 15 秒。

  具体步骤为:

  企业管理器中的设置:

  1、在企业管理器中,选择菜单上的"工具",再选择"选项";

  2、在弹出的"SQL Server企业管理器属性"窗口中,点击"高级"选项卡;

  3、在"连接设置"下的"登录超时(秒)"右边的框中输入一个比较大的数字,如 30。

  查询分析器中的设置:

  单击“工具”->"选项"->"连接"; 将登录超时设置为一个较大的数字,连接超时改为0。

  四、应用程序连接失败

  以上的三种错误信息都是发生在 SQL Server 自带的客户端工具中,在应用程序中我们也会遇到类似的错误信息,例如:

Microsoft OLE DB Provider for SQL Server (0x80004005)
[DBNETLIB][ConnectionOpen (Connect()).]Specified SQL server not found.
Microsoft OLE DB Provider for SQL Server (0x80004005)

  用户 'sa' 登录失败。原因: 未与信任 SQL Server 连接相关联。

Microsoft OLE DB Provider for ODBC Drivers 错误 '80004005'.
[Microsoft][ODBC SQL Server Driver]超时已过期.

  如果遇到连接超时的错误,我们可以在程序中修改 Connection 对象的超时设置,再打开该连接。例如:

<%
Set Conn = Server.CreateObject("ADODB.Connection")
DSNtest="DRIVER={SQL Server};SERVER=ServerName;UID=USER;PWD=password;DATABASE=mydatabase"
Conn. Properties("Connect Timeout") = 15 '以秒为单位
Conn.open DSNtest
%> 

  如果遇到查询超时的错误,我们可以在程序中修改 Recordset 对象的超时设置,再打开结果集。例如:

Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
. . .
cmd1 = txtQuery.Text
Set rs = New ADODB.Recordset
rs.Properties("Command Time Out") = 300
'同样以秒为单位,如果设置为 0 表示无限制
rs.Open cmd1, cn
rs.MoveFirst
. . . 

  五、小结

  本文针对大部分用户在使用 SQL Server 过程中常见的连接失败的错误,重点讨论了在使用 SQL Server 客户端工具以及用户开发的应用程序两种情况下,如何诊断并解决连接失败的错误。看过本文以后,相信每一个读者都会对 SQL Server 的连接工作原理、身份验证方式以及应用程序开发等有一个较为全面而深入的了解。

本文作者:

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
When should you use a composite index versus multiple single-column indexes?When should you use a composite index versus multiple single-column indexes?Apr 11, 2025 am 12:06 AM

In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)Apr 10, 2025 am 09:36 AM

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL: Essential Skills for DevelopersMySQL and SQL: Essential Skills for DevelopersApr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

Describe MySQL asynchronous master-slave replication process.Describe MySQL asynchronous master-slave replication process.Apr 10, 2025 am 09:30 AM

MySQL asynchronous master-slave replication enables data synchronization through binlog, improving read performance and high availability. 1) The master server record changes to binlog; 2) The slave server reads binlog through I/O threads; 3) The server SQL thread applies binlog to synchronize data.

MySQL: Simple Concepts for Easy LearningMySQL: Simple Concepts for Easy LearningApr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL: A User-Friendly Introduction to DatabasesMySQL: A User-Friendly Introduction to DatabasesApr 10, 2025 am 09:27 AM

The installation and basic operations of MySQL include: 1. Download and install MySQL, set the root user password; 2. Use SQL commands to create databases and tables, such as CREATEDATABASE and CREATETABLE; 3. Execute CRUD operations, use INSERT, SELECT, UPDATE, DELETE commands; 4. Create indexes and stored procedures to optimize performance and implement complex logic. With these steps, you can build and manage MySQL databases from scratch.

How does the InnoDB Buffer Pool work and why is it crucial for performance?How does the InnoDB Buffer Pool work and why is it crucial for performance?Apr 09, 2025 am 12:12 AM

InnoDBBufferPool improves the performance of MySQL databases by loading data and index pages into memory. 1) The data page is loaded into the BufferPool to reduce disk I/O. 2) Dirty pages are marked and refreshed to disk regularly. 3) LRU algorithm management data page elimination. 4) The read-out mechanism loads the possible data pages in advance.

MySQL: The Ease of Data Management for BeginnersMySQL: The Ease of Data Management for BeginnersApr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor