Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a database in postgresql, and I have defined a tables named customer with 3 columns:

1. ID => Type: int
2. Name => Type: varchar(50)
3. Email => Type: varchar(50)

What I have tried:

I have defined a sequence named customer_id to fill ID automatically so I use the following code to insert data into the table:
NpgsqlCommand cmd1 = new NpgsqlCommand("insert into customer values (nextval('customer_id'), + '" + textbox1.Text + "' , '" + textBox2.Text + "');", con1);
cmd1.ExecuteNonQuery();

But I get the following exception when I try to add these data:
Name: Naser
Email: naser@yahoo.com

22P02: invalid input syntax for type double precision: "Naser"
Posted
Updated 29-Dec-19 20:31pm
v2
Comments
RickZeeland 30-Dec-19 2:39am    
You can test your SQL insert query in pgAdmin, my guess is that you need something like:
insert into customer (id, name, email) values (nextval('customer_id'), 'Naser', 'naser@yahoo.com';
Naser Sadeghi 30-Dec-19 10:41am    
I tested the same query in pgAdmin and it works well. The problem shows up when I want to insert data from C# windows form application.

1 solution

C#
NpgsqlCommand cmd1 = new NpgsqlCommand("insert into customer values (nextval('customer_id'), + '" + textbox1.Text + "' , '" + textBox2.Text + "');", con1);

Not necessary a solution to your question, but another problem you have.
Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input a name like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability, and the crash is the least of the problems, a malicious user input and it is promoted to SQL commands with all credentials.
SQL injection - Wikipedia[^]
SQL Injection[^]
SQL Injection Attacks by Example[^]
PHP: SQL Injection - Manual[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]
How can I explain SQL injection without technical jargon? - Information Security Stack Exchange[^]
 
Share this answer
 
Comments
Naser Sadeghi 30-Dec-19 10:47am    
I am aware of SQL Injection but here my problem is something else. I know how to avoid SQL Injection. Please post answers or comments that help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900