','附近的语法无效 - SQL C#错误

时间:2010-08-20 02:18:42

标签: c# sql

我一直收到以下错误:(C#WinForms)

  

“','”

附近的语法无效

我有以下代码:

    // Initialize and instantiate a new reader object.
    SqlDataReader slrr = null;
    // Send command.
    System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("SELECT ActivationCode FROM CAccounts WHERE ActivationCode=" +
    _activationcode, connection);

    slrr = command.ExecuteReader();

    // read result(s) of command.
    while (slrr.Read())
    {
        if (slrr["ActivationCode"].ToString() == _activationcode.Text)
        {
            stat.Text = "It appears that these details have already been registered.";
            Properties.Settings.Default.GU = false;
            Properties.Settings.Default.Save();
        }
        else
        {
            System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand(
                "INSERT INTO CAccounts (FirstName, LastName, Country, Gender, EmailAddress, ActivationCode, ClientID, IsActivated) VALUES ('" +
                _firstname.Text + "', '" + _lastname.Text + "', '" + _country.Text + "', '" + gender + "', '" +
                _email.Text + "', '" + _activationcode.Text + "', '" + _clientid.Text + "', '" + "yeh'", connection);

            comm.ExecuteNonQuery();

            stat.Text = "Product Activation succeeded.";
            Properties.Settings.Default.GU = true;
            Properties.Settings.Default.FirstName = _firstname.Text;
            Properties.Settings.Default.LastName = _lastname.Text;
            Properties.Settings.Default.Country = _country.Text;
            Properties.Settings.Default.Gender = gender;
            Properties.Settings.Default.DateOfBirth = _dateofbirth.Text;
            Properties.Settings.Default.EmailAddress = _email.Text;
            Properties.Settings.Default.ActivationID = _activationcode.Text;
            Properties.Settings.Default.ClientID = _clientid.Text;
            Properties.Settings.Default.IsActivated = true;
            Properties.Settings.Default.Save();
        }
    }
}
catch (Exception exception)
{
    // Catch the exception and throw an error.
    stat.Text = exception.Message;
}

我完全不知道我做错了什么。有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:3)

考虑构造INSERT命令的代码行。如果任何字段包含撇号,您认为会发生什么?

你猜对了,声明变得无效。

您可以使用SqlCommand.Parameters解决此问题。请参阅该页面上的示例。

当然,这同样适用于代码段顶部附近的SELECT命令。

答案 1 :(得分:0)

而不是:

"', '" + "yeh'", connection);

应该是:

"', '" + "yeh')", connection);

你忘了关闭你的VALUES括号,这就是原因。

答案 2 :(得分:-1)

如果IsActivated是某种布尔值,'yeh'是否有效?我首先将SQL命令构建为字符串变量并将其打印出来。所有连接都有问题。在将SQL字符串传递给命令对象之前将其打印出来会使错误变得明显。

我不是C#专家,但是没有更好的方法来获取字符串列表,用引号括起来,并使用“,”作为分隔符加入结果?类似于以下Python片段的内容使构建SQL字符串的错误更少:

>>> s = str.join(', ', ("'{0}'".format(x) for x in ['bob', 'alex', 'guido']) )
>>> print s
'bob', 'alex', 'guido'

然后再次,让别人构建SQL以避免因SQL注入引起的小尴尬,你会好得多。