簡體   English   中英

使用 SQL 服務器連接字符串出現錯誤

[英]Getting an error using SQL Server connection string

public void DataGrid_Data()
{
    // 2 second delay before loading DataGrid
    var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
    timer.Start();
    timer.Tick += (sender, args) =>
        {
            timer.Stop();

            // Attempt to connect to SQL Server database and populate DataGrid with database tables. 
            try
            {
                string connectionString = (@"Data Source=ComputerName\SQLEXPRESS;Initial Catalog=CustomerRelations;Integrated Security=True;");
                SqlConnection connection = new SqlConnection(connectionString);

                SqlCommand cmd = new SqlCommand("SELECT `hb_disputes`.`DSP_ID`, `hb_disputes`.`ACCOUNT`, `hb_disputes`.`CUST_NAME`,`hb_disputes`.`PREM_ADDR`, `hb_status`.`Status`, `hb_disputes`.`OPENED`, `hb_disputes`.`DEADLINE`, `hb_rpttype`.`ReportType`, `hb_ratetype`.`Rate Type`FROM `hb_disputes` LEFT JOIN `hb_status` ON `hb_disputes`.`STATUS` = `hb_status`.`STSID` LEFT JOIN `hb_rpttype` ON `hb_disputes`.`RPTTYPE` = `hb_rpttype`.`RPTID` LEFT JOIN `hb_ratetype` ON `hb_disputes`.`REV_CLS` = `hb_ratetype`.`RTID`; ", connection);
                connection.Open();

                DataTable dt = new DataTable();
                dt.Load(cmd.ExecuteReader());

                connection.Close();

                dtGrid.DataContext = dt;
            }
            catch
            {
                MessageBox.Show("Database connection is not available at this time. Please contact your database administrator ");
            }
        };
}

我一直在為我的應用程序使用 MYSQL,我決定切換到 SQL 服務器。 我在 SQL 服務器中重建了數據庫並將其連接到 Visual Studio,它為我提供了連接字符串。 但是,由於計算機名和SQLEXPRESS之間有一個“\”,我得到一個

無法識別的轉義序列

錯誤。 我嘗試使用“@”和“\”,但仍然無法連接到數據庫。 我也只是簡單地將MySqlCommand替換為SqlCommand

由此

   string connectionString = (@"Data Source=ComputerName\SQLEXPRESS;Initial Catalog=CustomerRelations;Integrated Security=True;");

   string connectionString = ("Data Source=ComputerName\\SQLEXPRESS;Initial Catalog=CustomerRelations;Integrated Security=True;");

讓我知道它是否有幫助

2 個反斜杠

歡迎來到該站點...從我的 C#/SQL-Server 工作中,我的連接字符串是不同的,例如

Server=myServerName\theInstanceName; Database=myDataBase; Trusted_Connection=yes;

與你的相比

Data Source=ComputerName\SQLEXPRESS;Initial Catalog=CustomerRelations;Integrated Security=True;

不確定這是否是您的連接問題。

暫無
暫無

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

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