写法:插入表除X之外的所有内容,if语句

发布于 2024-12-09 17:37:05 字数 935 浏览 0 评论 0原文

这个社区有史以来的第二个问题!我是一个菜鸟,我的弱点是循环内或循环之间的 if 语句以及其他 if 语句。

这是我的场景。此方法将任何内容插入数据库,但我想验证某些内容。我不希望在数据库中添加任何内容,而是不希望输入任何以“LIFT”开头的内容,我希望该方法跳过该行并继续下一行。有什么办法可以将其编程到这个方法中吗?或者我需要写一个新方法吗?非常感谢!

      public bool BatchInsert(string table, string[] values)
{
    string statement = "INSERT INTO " + table + " VALUES(";
    for (var i = 0; i < values.Length - 1; i++)
    {
        if(values[i].Contains("'")){
            values[i] = values[i].Replace("'", "''");
        }
        statement += "'"+values[i]+"', ";
    }
    statement += "'" + values[values.Length - 1] + "');";

    SqlCommand comm = new SqlCommand(statement, connectionPCICUSTOM);
    try
    {
        comm.Connection.Open();
        comm.ExecuteNonQuery();
    }
    catch (Exception e)
    {
        KaplanFTP.errorMsg = "Database error: " + e.Message;
    }
    finally
    {
        comm.Connection.Close();
    }

    return true;

}

Second question of all time on this community! I am a noob and my weakness are if statements within or amoungst loops and other if statements.

So here is my scenario. This method inserts anything into a database, but I want to validate something. Instead of adding anything into the database, I do not want anything entered in that begins with "LIFT", I want the method to skip over that line and proceed to the next one. Is there a way I can program this into this method? Or do I need to write a new method? Thanks a bunch!

      public bool BatchInsert(string table, string[] values)
{
    string statement = "INSERT INTO " + table + " VALUES(";
    for (var i = 0; i < values.Length - 1; i++)
    {
        if(values[i].Contains("'")){
            values[i] = values[i].Replace("'", "''");
        }
        statement += "'"+values[i]+"', ";
    }
    statement += "'" + values[values.Length - 1] + "');";

    SqlCommand comm = new SqlCommand(statement, connectionPCICUSTOM);
    try
    {
        comm.Connection.Open();
        comm.ExecuteNonQuery();
    }
    catch (Exception e)
    {
        KaplanFTP.errorMsg = "Database error: " + e.Message;
    }
    finally
    {
        comm.Connection.Close();
    }

    return true;

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沉睡月亮 2024-12-16 17:37:05

一些提示。不要 += 字符串类型,因为它会降低性能。我也更喜欢 foreach 循环,因为代码更干净、更容易阅读/不太可能弄乱索引。还可以使用 using 语句来确保正确处置。

假设您有对 System.Linq 的引用,您可以使用以下内容。我没有测试它,但它应该可以工作:

public bool BatchInsert(string table, IEnumerable<string> values)
    {
        var sql = new StringBuilder();
        sql.Append("INSERT INTO " + table + " VALUES(");

        var newValues = values.Where(x => !x.StartsWith("LIFT")).Select(x => string.Format("'{0}'", x.Replace("'", "''")));
        sql.Append(string.Join("","", newValues.ToArray()));
        sql.Append(")");

        using (var comm = new SqlCommand(statement, connectionPCICUSTOM))
        {
            try
            {
                comm.Connection.Open();
                comm.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                KaplanFTP.errorMsg = "Database error: " + e.Message;
            }
            finally
            {
                comm.Connection.Close();
            }
        }
        return true;
    }

A couple hints. Don't += string types as it slows down performance. I also prefer foreach loops as the code is cleaner and easier to read/less likely to mess up the index. Also make using of the using statement to ensure proper disposal.

Assuming you have a reference to System.Linq you can use the following. I didn't test it but it should work:

public bool BatchInsert(string table, IEnumerable<string> values)
    {
        var sql = new StringBuilder();
        sql.Append("INSERT INTO " + table + " VALUES(");

        var newValues = values.Where(x => !x.StartsWith("LIFT")).Select(x => string.Format("'{0}'", x.Replace("'", "''")));
        sql.Append(string.Join("","", newValues.ToArray()));
        sql.Append(")");

        using (var comm = new SqlCommand(statement, connectionPCICUSTOM))
        {
            try
            {
                comm.Connection.Open();
                comm.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                KaplanFTP.errorMsg = "Database error: " + e.Message;
            }
            finally
            {
                comm.Connection.Close();
            }
        }
        return true;
    }
夜空下最亮的亮点 2024-12-16 17:37:05

如果您的目标是迭代“值”集合,保持以“lift”开头的值及其相应的列不变,则可能需要修改 INSERT 查询的构建方式。您将根据需要添加列,而不是假设每个值都会被考虑在内。基本上,您需要使用以下形式:

INSERT INTO tablename (col1, col2...) VALUES (val1, val2...)

例如:

string statement = "INSERT INTO tablename ";
string columns = "(";
string values = "(";
for (var i = 0; i < values.Length - 1; i++)
{
     //if values doesn't contain lift, add it to the statement
     if(!values[i].contains("LIFT")){
          //columnName is a collection of your db column names
          columns += "'"+columnName[i]+"'";
          values += "'"+values[i]+"'";
     }
 }
 columns += ")";
 values += ")";
 statement += columns +" VALUES " + values;

就像一些评论所述,这种方法会导致 SQL 注入。谨慎使用。

编辑:抱歉,我错过了您所说的“以“LIFT”开头”。将 .contains() 行修改为以下内容:

if(!values[i].StartsWith("LIFT")){

If your goal is to iterate through your collection of 'values', leaving values beginning with 'lift' and their corresponding columns untouched, you may have to revise the way your INSERT Query is constructed. You will add columns as needed, instead of assuming that each value will be accounted for. Basically, you will need to use the form:

INSERT INTO tablename (col1, col2...) VALUES (val1, val2...)

For example:

string statement = "INSERT INTO tablename ";
string columns = "(";
string values = "(";
for (var i = 0; i < values.Length - 1; i++)
{
     //if values doesn't contain lift, add it to the statement
     if(!values[i].contains("LIFT")){
          //columnName is a collection of your db column names
          columns += "'"+columnName[i]+"'";
          values += "'"+values[i]+"'";
     }
 }
 columns += ")";
 values += ")";
 statement += columns +" VALUES " + values;

Like some of the comments have stated, this approach opens you up to SQL injections. Use with caution.

EDIT : Sorry, I missed where you said 'starts with 'LIFT'. Revise the .contains() line to the following:

if(!values[i].StartsWith("LIFT")){
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文