1

在代码后面我有这个:

 protected void ButtonSave_Click(object sender, EventArgs e)
        {
            Guid guid = (Guid)Membership.GetUser().ProviderUserKey;
            string name = TextBoxCategoryName.Text;
           // string user = Membership.GetUser().UserName;
            this.connection.Open();
            command = connection.CreateCommand();
            command.CommandText = "insert into ProfitCategories(name, IdUser) values ( '" + name + "', "+guid+" )";
            command.ExecuteNonQuery();

            connection.Close();
        }

但这给出了错误:Incorrect syntax near 'a8'. 如何从当前用户获取 GUID 并插入数据库

4

2 回答 2

3

尽管 Mike 已经为您提供了答案,但我想提请您注意使用存储过程而不是 sql 查询

  try
  {
      Guid guid = (Guid)Membership.GetUser().ProviderUserKey;
      string name = TextBoxCategoryName.Text;

       using (SqlConnection con = new SqlConnection(sqlConnection))
            {
            SqlCommand command = new SqlCommand("sp_InsertUserDatails", sqlConnection);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("@name", SqlDbType.VarChar).Value = name ;
            command.Parameters.Add("@IdUser", SqlDbType.VarChar).Value = guid ;
            sqlConnection.Open();
            return command.ExecuteNonQuery();
            sqlConnection.Close();
            }
  }
catch (SqlException ex)
  {
     Console.WriteLine("SQL Error" + ex.Message.ToString());
     return 0;
  }

这里是存储过程

    CREATE PROCEDURE sp_InsertUserDatails 
(
    @name varchar(100),
    @IdUser varchar(100)
)
AS
BEGIN
    insert into dbo.ProfitCategories(name, IdUser) 
    values (@name, @IdUser)
END
GO
于 2013-04-01T22:42:24.043 回答
1

小问题:您的 GUID 周围缺少单引号。它应该是:

command.CommandText = "insert into ProfitCategories (name, IdUser) values ( '" + name + "', '" + guid + "' )";

但不要这样做。

最大的问题:如果你这样修复,你就有被 SQL 注入的风险。使用 SQL 语句的参数来适当地修复,或使用存储过程。

阅读:

MSDN SqlCommand.Parameters

SQL 注入

于 2013-04-01T22:38:30.987 回答