I am writing code that will prepare my database for my application. There are some repetitive SQL statements in the code when I create the table, and I want to hide them in some methods (at the moment there are only two of them: creating a primary key and creating a table identifier with automatic increment in Postgres). For a simple case of a primary key, I first wrote a function like this:
public void MakePrimaryKey(DbConnection conn, string tblName, string colName)
{
conn.Execute(@"
ALTER TABLE ""@tblName""
ADD CONSTRAINT ""@constrName"" PRIMARY KEY(""@colName"")
", new { tblName = tblName,
constrName = tblName + "_pkey",
colName = colName } );
}
After long errors with errors and exceptions, I finally came to the conclusion that using parameters in this way is not supported, so I switched to the traditional call string.Format(), and everything was fine.
But I am not very satisfied. Is this way of using parameters really not supported? If so, in what places can I use these parameters safely? Only for the variable parts of an SQL query — for example, where can I use stored procedure parameters?
source
share