如果 SQL 查询包含保留关键字,如何避免 SqlException?

How to avoid SqlException if SQL query contains reserved keyword?

string connection = ConfigurationManager.ConnectionStrings["Table"].ConnectionString;
using (SqlConnection con = new SqlConnection(connection))
{
    using (SqlCommand cmd = new SqlCommand("SELECT * FROM Table", con))
    {
        using (SqlDataAdapter da = new SqlDataAdapter())
        {
            da.SelectCommand = cmd;
            using (DataTable dt = new DataTable())
            {
                da.Fill(dt);//This line throws exception
                return dt;

我有这段代码,我想用它从网格中获取选定的数据并插入另一个 table。调试时,它导致我在 da.Fill(dt); 行出现异常。

以下是抛出的异常:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: Incorrect syntax near the keyword 'Table'.

如异常所述,“Table”是 SQL 中的关键字。如果您想在查询中将其用作 table 名称,则必须将 select 语句更改为

SELECT * FROM [Table]