在Excel导入期间连接到SQL Server时,登录失败,导致用户错误

时间:2011-11-01 07:21:51

标签: c# sql-server visual-studio sql-server-2005 visual-studio-2005

我正在通过C#Visual Studio 2005将数据从excel电子表格导入到SQLServer 2005.我想我的连接已经启动,因为直到最后一部分我没有收到任何错误,我的用户名和sql连接字符串密码被提示无效。下面是错误代码和我的代码。

enter image description here http://i.stack.imgur.com/MjRXm.png

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    public static string path = @"c:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\insqlserver\studentsheet1.xls";
    public static string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";

    protected void Page_Load(object sender, EventArgs e)
    {
        // Connection String to Excel Workbook
        //**string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\insqlserver\studentsheet.xls';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";


        // Create Connection to Excel Workbook
using (OleDbConnection connection =
             new OleDbConnection(connStr))
{
    OleDbCommand command = new OleDbCommand
            ("Select StudentName,RollNo,Course FROM [Sheet1$]", connection);

    connection.Open();

    // Create DbDataReader to Data Worksheet
    using (DbDataReader dr = command.ExecuteReader())
    {
        // SQL Server Connection String
        string sqlConnectionString = "Data Source=<IP>;Initial Catalog=<database>;User ID=<userid>;Password=<password>;Integrated Security=True";

        // Bulk Copy to SQL Server
        using (SqlBulkCopy bulkCopy =
                   new SqlBulkCopy(sqlConnectionString))
        {
            bulkCopy.DestinationTableName = "ExcelData";
            bulkCopy.WriteToServer(dr); <------Error appeared at this line
        }
    }
}
}
}

1 个答案:

答案 0 :(得分:5)

从数据库连接字符串中删除“集成安全性”部分。这是设置您的连接使用Windows身份验证而不是SQL身份验证。在http://www.connectionstrings.com/

上查找示例