简体   繁体   中英

Verifying if a word is reserved in Microsoft Access SQL using c#

I am building a DAL class for my school project. The main Idea is for it to be generic. Everything is fine until I get to the reserved words part. I made a method that works with "Password", Which is a reserved word

       public static void AddRow(string name, object[] values)
    {
        string com = "SELECT TOP 1 * FROM " + name;
        DataTable dt = OleDbhelper.fill(com);
        if (dt.Columns.Count - 1 == values.Length)
        {
            string sql = "INSERT INTO " + name + " (";
            for (int i = 1; i < dt.Columns.Count; i++)
            {
                if (dt.Columns[i].ColumnName == "Password")
                    sql += "[";
                sql += dt.Columns[i].ColumnName;
                if (dt.Columns[i].ColumnName == "Password")
                    sql += "]";
                if (i != dt.Columns.Count - 1)
                    sql += ",";
                else
                    sql += ") ";
            }
            sql += "VALUES (";
            for (int i = 0; i < values.Length; i++)
            {
                if (dt.Columns[i + 1].DataType.ToString() == "System.String")
                    sql += "'" + values[i].ToString() + "'";
                else
                    sql += values[i].ToString();
                if (i != dt.Columns.Count - 2)
                    sql += ",";
                else
                    sql += ") ";
            }
            OleDbhelper.Execute(sql);
        }
    }

What I want to do is to replace the

if (dt.Columns[i].ColumnName == "Password")

Line into a something that will work with all the reserved words ("Level" for example). I've been checking the internet and tried different methods for hours now, but i still cant find a way to do it. I also can't find a full updated list, only partially made lists that contain only part of the reserved words.

I'm lost here. I'll gladly accept any ideas of how to fix this problem.

You do not need to check if the column name is a reserved word to decide whether to put [] s around it or not. It is safe to just add brackets whatever the name, this does not break anything.

So this part of the code:

if (dt.Columns[i].ColumnName == "Password")
    sql += "[";
sql += dt.Columns[i].ColumnName;
if (dt.Columns[i].ColumnName == "Password")
    sql += "]";

can just be rewritten as:

sql += "[" + dt.Columns[i].ColumnName + "]";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM