所以我想我会粘贴整个东西,但foreach循环部分不起作用。这是针对添加页面的,当我发布并尝试搜索时,这是错误页面:https://i.imgur.com/9WYBE4G.png。此外,这是添加页面的样子:http://i.imgur.com/8QkFLzW.png。 参考错误页面,它说“附近的语法不正确”(“”。有谁知道如何解决这个问题?
在GETDATE()
之前添加了逗号public void ProcessRequest(HttpContext context)
{
// create new Sql connection
SqlConnection connection = new SqlConnection(Properties.Settings.Default.ConnectionString);
connection.Open();
// insert into query
string query = "INSERT INTO license_info (SoftwareTitle, SoftwareVersion, SoftwareVendor, SoftwareLastUpdate)";
query += " VALUES (";
// first is a true boolean statement
// if bool not first, then false
bool first = true;
// might not need this (foreach loop). if not listed first, add key + -@
foreach (string key in context.Request.Form.AllKeys)
{
// add comma (,) if not first
if (!first)
{
query += ", ";
}
query += "@" + key;
first = false;
}
// if not listed first, apply GETDATE() function
if (!first)
{
query += ", GETDATE());";
}
first = false;
SqlCommand command = new SqlCommand(query, connection);
foreach (string key in context.Request.Form.AllKeys)
{
command.Parameters.AddWithValue("@" + key, context.Request.Form[key]);
}
command.ExecuteNonQuery();
connection.Close();
// end connection
// connection.Close();
// redirect to admin
context.Response.Redirect(Properties.Settings.Default.BaseURL + @"/admin");
}
答案 0 :(得分:1)
通过使用已知的表单键来获取值,可以大大简化这一过程。无需循环或构建任何类型的动态查询。
public void ProcessRequest(HttpContext context)
{
// create new Sql connection
const string query = "INSERT INTO license_info (SoftwareTitle, SoftwareVersion, SoftwareVendor, SoftwareLastUpdate) VALUES (@SoftwareTitle, @SoftwareVersion, @SoftwareVendor, @SoftwareLastUpdate)";
using(SqlConnection connection = new SqlConnection(Properties.Settings.Default.ConnectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
// todo: Update the SqlDbTypes and length according to your schema
command.Parameters.Add(new SqlParameter("@SoftwareTitle", SqlDbType.VarChar, 200)).Value = context.Request.Form["TitleKey"];
command.Parameters.Add(new SqlParameter("@SoftwareVersion", SqlDbType.VarChar, 200)).Value = context.Request.Form["VersionKey"];
command.Parameters.Add(new SqlParameter("@SoftwareVendor", SqlDbType.VarChar, 200)).Value = context.Request.Form["VendorKey"];
command.Parameters.Add(new SqlParameter("@SoftwareLastUpdate", SqlDbType.DateTime)).Value = DateTime.Now;
connection.Open();
command.ExecuteNonQuery();
}
此外,您应该使用using
块来包装实现IDisposable
的类型,在这种情况下,即使存在异常,也始终确保数据库连接已关闭。