在代码背后我有这个:
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并插入数据库
答案 0 :(得分:3)
虽然迈克已经向您提供了答案,但我想提请您注意使用存储过程而不是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
答案 1 :(得分:1)
小问题:您缺少GUID周围的单引号。它应该是:
command.CommandText = "insert into ProfitCategories (name, IdUser) values ( '" + name + "', '" + guid + "' )";
但不要这样做。
最大的问题:如果您这样修复,您将面临SQL注入的风险。使用SQL语句的参数来正确修复或使用存储过程。
读: