繁体   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