【发布时间】:2020-07-15 04:50:43
【问题描述】:
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 Server。我在 SQL Server 中重建了数据库并将其连接到 Visual Studio,它为我提供了连接字符串。但是,由于计算机名称和 SQLEXPRESS 之间有一个“\”,所以我得到一个
无法识别的转义序列
错误。我尝试使用“@”和“\”,但仍然无法连接到数据库。我也只是简单地将我的MySqlCommand 替换为SqlCommand。
【问题讨论】:
-
到目前为止,您已经正确地遵循了线索并进行了适当的更改。对此表示敬意。你得到什么异常?您的
catch块需要异常类型才能检查异常;像这样盲目地捕捉不是一个好主意。此外,虽然 MySQL 使用反引号来引用名称,但 SQL Server 使用方括号(如果您启用了QUOTED_IDENTIFIER,则使用双引号),因此您需要相应地修改您的查询,然后才能准备好执行查询。 -
我的 SQL 语句需要更改我需要使用 [ ] 而不是 ``
标签: c# sql sql-server wpf connection-string