簡體   English   中英

在 c# 中連接到 SQL '連接無效' 錯誤

[英]Connecting to SQL in c# 'Connection is invalid' error

我正在努力在我的 windows form c# 程序和沒有用戶名或密碼的 sqlexpress 數據庫之間建立連接,身份驗證類型是 windows 身份驗證。

我相信問題出在字符串上,但我不明白,我可以連接到 Windows 控制台應用程序,但不能連接到 Windows 窗體應用程序。 我試過各種連接字符串..

最后一行產生錯誤

System.ArgumentException: '連接無效'

任何積極的幫助都受到高度贊賞,到處尋找並搜索 SO,但找不到類似的問題

        {
            // New instance of ExcelEngine created (opening excel with no workbooks open)
            using (ExcelEngine excelEngine = new ExcelEngine())
            {
                // Create excel application object
                IApplication application = excelEngine.Excel;

                //Assigns default application version
                application.DefaultVersion = ExcelVersion.Excel2013;

                // New workbook created with one worksheet
                IWorkbook workbook = application.Workbooks.Create(1);

                //Access a worksheet in workbook
                IWorksheet worksheet = workbook.Worksheets[0];

                if (worksheet.ListObjects.Count == 0)
                {
                    //Estabilishing the connection in the worksheet 
                    string connectionString = "Server =NBE\\SQLEXPRESS; Initial Catalog = BikeStores; Trusted_Connection = True";
                    // "Data Source = NICHOLASBOACHIE\\SQLEXPRESS; Initial Catalog = BikeStores; Integrated Security = SSPI";

                    string query = "SELECT * FROM [BikeStores].[sales].[staffs]";

                    IConnection connection = workbook.Connections.Add("SQLConnection", "Connection with SQL Server", connectionString, query, ExcelCommandType.Sql);

                    //Create Excel table from external connection (intitate worksheet)
                    worksheet.ListObjects.AddEx(ExcelListObjectSourceType.SrcQuery, connection, worksheet.Range["A1"]);


                } 

看起來您的連接字符串格式無效。 System.Data.SqlClient 庫有一個 SqlConnectionStringBuilder 類,您可能會發現它很有用。

它記錄在這里

自從我使用這個類已經有一段時間了,但類似這樣:

SqlConnection myConnection = new SqlConnection();
SqlConnectionStringBuilder myBuilder = new SqlConnectionStringBuilder();
myBuilder.IntegratedSecurity = true;
myBuilder.InitialCatalog = "BikeStores";
myBuilder.DataSource = "NBE\\SQLEXPRESS";
myConnection.ConnectionString = myBuilder.ConnectionString;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM