【发布时间】:2021-05-10 21:08:19
【问题描述】:
我正在检索一个 HTTP 响应,我正在将值反序列化到 Azure SQL 数据库中。我找不到任何方法来格式化 SQL 命令以将字符串变量更新到表的最后一条记录中。目的是用每个新令牌覆盖最后一条记录,以避免数据库维护要求。我可以像下面的示例中那样静态地写入一个值,但我需要它由变量动态传递,这似乎由于某种原因而放弃了语法或命令执行。不会抛出任何错误或异常——它什么也不做。
有人对我如何实现这一点有任何想法吗?下面列出了 SQL 特定的代码以供参考。
dynamic access = JsonConvert.DeserializeObject(response.Content);
string accessToken = access.access_token;
string timestamp = centralTime.ToString();
System.Data.SqlClient.SqlConnection connect = new System.Data.SqlClient.SqlConnection(connectionString);
System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand();
command.CommandType = System.Data.CommandType.Text;
// this works as needed to insert a new record where required, but builds record counts over time
// command.CommandText = @"INSERT INTO AccessTokens (Token, LastRefreshDate) VALUES (@Token, @LastRefreshDate)";
// command.Parameters.AddWithValue("@Token", accessToken);
// command.Parameters.AddWithValue("@LastRefreshDate", centralTime);
// I've tried as many variations as possible based on what's available online upon searching; these are two examples that don't work
// command.CommandText = @"UPDATE TOP 1 * FROM AccessTokens (Token, LastRefreshDate) VALUES (@Token, @LastRefreshDate)";
// command.CommandText = @"UPDATE AccessTokens SET Token = " + accessToken + " , LastRefreshDate = " + timestamp;
// this will update the record with the new value, but it's static
command.CommandText = @"UPDATE AccessTokens SET Token = 12345";
string test = "test";
// attempting to update with a string variable does not work, which is the desired outcome in order to maintain only one record with a dynamically changing value over time
// command.CommandText = @"UPDATE AccessTokens SET Token = " + test;
command.Connection = connect;
connect.Open();
command.ExecuteNonQuery();
connect.Close();
【问题讨论】:
标签: sql asp.net sql-server