I am trying to use PostgreSQL with C# (not asp.net) via Npqsql, I created a table with the name GenData with SQL;
CREATE TABLE gendata
(
empname text NOT NULL,
pyrll text NOT NULL,
contracno text,
expird date,
dtbrth date,
plbrth text,
cid text,
passport text,
jndt date,
postn text,
dept text,
hmtwn text,
familymen numeric,
contno text,
CONSTRAINT gendata_pkey PRIMARY KEY (pyrll)
)
I tried to insert to the table with the following code:
String sql = String.Format("INSERT INTO GenData VALUES ({0},{1},{2},'{3}',{4},{5},{6},{7},{8},{9},{10},{11},{12},{13});"
,textBox1.Text
,textBox2.Text
,textBox3.Text
,textBox4.Text
,textBox5.Text
,textBox6.Text
,textBox7.Text
,textBox8.Text
,textBox9.Text
,textBox10.Text
,textBox11.Text
,textBox12.Text
,textBox13.Text
,textBox14.Text);
But I always get an exception like:
Since you are not using SQL Parameters, but directly embed values into the string (which is considered quite bad practice), you should follow SQL syntax. In your particular situation, you should wrap all string parameters into
'.Better way is to use
SQLParameterclass to allow .NET perform all necessary transformations on input data, escape the data to avoid sql-injections and so on. I’m not quite familiar with Npgsql, but I’m almost sure it follows the same guidelines as the other .NET database providers, so you should be able to use theSQLParameterclass the same way.