Matthew
Matthew

Reputation: 3234

C# NpgsqlCommand - AddWithValue is not substituting

So let me first off state that I know there are other questions with the same issue--I've read most of them and tried different things... Nothing worked.. So please don't close because of "Duplicate" because those ARE NOT working for me.

I am also using Postgres as my database.

Thanks for assistance in advanced.

public static string RetrieveEntry(string table, string lookup)
        {
            Console.WriteLine("RetrieveEntry");
            if (!IsConnected())
            {
                return "Request Failed";
            }
            string str = "No poll were found that contained that info.";
            string sqlstring = "SELECT * FROM "+table+" WHERE topic = '@t' OR description LIKE '@d' OR started_by = '@sb'";
            NpgsqlCommand sql = new NpgsqlCommand(sqlstring,conn);
            sql.Parameters.AddWithValue("@t", lookup);
            sql.Parameters.AddWithValue("@d", "%" + lookup + "%");
            sql.Parameters.AddWithValue("@sb", lookup);
            NpgsqlDataAdapter adap = new NpgsqlDataAdapter(sqlstring,conn);
            DataSet ds = new DataSet();
            adap.Fill(ds);
            Console.WriteLine("Table: "+ds.Tables[0].TableName+"; Tables: "+ds.Tables.Count+"; Rows: "+ds.Tables[0].Rows.Count);
            if (ds.Tables[0].Rows.Count > 0) str = ""; //Remove default string

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                str += "Topic:\t" + dr["topic"] +
                    "\nDesc:\t" + dr["description"].ToString().Substring(0, Math.Min(25, dr["description"].ToString().Length)) + "\n\n";
            }

            return str;

        }

Upvotes: 1

Views: 1297

Answers (2)

beatcoder
beatcoder

Reputation: 723

I know it's a bit late, but I really think You shouldn't use the @ character in the AddWithValue parameter.

Something like:

        sql.Parameters.AddWithValue("t", lookup);
        sql.Parameters.AddWithValue("d", "%" + lookup + "%");
        sql.Parameters.AddWithValue("sb", lookup);

Upvotes: 1

farzaaaan
farzaaaan

Reputation: 410

Would using a reader fix the issue?

ds.Load(NpgsqlDataReader reader = sql.ExecuteReader(CommandBehavior.CloseConnection));

from this answer

Upvotes: 1

Related Questions