I get this exception when I'm trying to run a simple SELECT query with my Visual Studio project:
当我尝试使用Visual Studio项目运行简单的SELECT查询时,我得到了这个异常:
System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'Table'.'
System.Data.SqlClient.SqlException:'关键字'Table'附近的语法不正确。
My code:
我的代码:
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Claudia\source\repos\WindowsFormsApp7\WindowsFormsApp7\Database1.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
loadlist();
}
private void loadlist()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
cn.Open();
// here I get the exception
cmd.CommandText = "SELECT * FROM Table";
dr = cmd.ExecuteReader();
if(dr.HasRows)
{
while (dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
else
{
listBox1.Items.Add("No items");
}
cn.Close();
}
}
I tried all methods I've known, I also tried to recreate the project form nothing but I get this exception every time. When I run the project, database is disconnecting. What can I do to solve this?
我尝试了所有已知的方法,我也尝试重新创建项目形式,但每次都得到这个例外。当我运行项目时,数据库正在断开连接。我该怎么做才能解决这个问题?
1 个解决方案
#1
4
Table
is a keyword for SQL Server. You need to escape it by wrapping it in square brackets:
Table是SQL Server的关键字。你需要通过将其包装在方括号中来逃避它:
cmd.CommandText = "SELECT * FROM [Table]";
Btw: Table
is of course not a very good table name.
顺便说一下:表当然不是一个非常好的表名。
#1
4
Table
is a keyword for SQL Server. You need to escape it by wrapping it in square brackets:
Table是SQL Server的关键字。你需要通过将其包装在方括号中来逃避它:
cmd.CommandText = "SELECT * FROM [Table]";
Btw: Table
is of course not a very good table name.
顺便说一下:表当然不是一个非常好的表名。