我是C#
和SQL
新手。
使用以下代码,我正在尝试创建新表,一切都如我所愿,但问题是:如果我命名一个以数字 (123MytableName
开头的表,则使用 textBox
它会抛出错误,说"'123MytableName'附近的语法不正确"
using (SqlConnection MyConnection = new SqlConnection())
using (SqlCommand MySQLCommand = new SqlCommand())
{
MyConnection.ConnectionString = " Data Source=localhost; Initial Catalog=TestDB ;Integrated Security=true;Max Pool Size=1024; Pooling=true";
MyConnection.Open();
MySQLCommand.CommandText = "CREATE TABLE "+textBox1.Text+" (Col1 int, Col2 varchar(50), Col money)";
MySQLCommand.Connection = MyConnection;
MySQLCommand.ExecuteNonQuery();
}
我读了这篇文章,但它没有帮助。
有人知道如何修复它,以便我可以创建以数字开头的表格吗?
谢谢
您可以通过用 []
括起来来转义表的名称:
MySQLCommand.CommandText = "CREATE TABLE ["+textBox1.Text+"] (Col1 int, Col2 varchar(50), Col money)";
// Here ---------------------------------^-----------------^