C
C#2y ago
Jona4Play

✅ PostgreSQL foreach() insert not working

Hey, currently working on a DB project for the first time with PostgreSQL and for some reason this insert operation inserts the first entry in the list for the length of the list into the DB resulting in mass duplicate entries of just the first entry of the list.
var sql = @"INSERT INTO outstanding(name) VALUES(@name)";
using var cmd = new NpgsqlCommand(sql, con);
foreach (var item in outstanding)
{
cmd.Parameters.AddWithValue("name",item);
cmd.Prepare();
cmd.ExecuteNonQuery();
}
var sql = @"INSERT INTO outstanding(name) VALUES(@name)";
using var cmd = new NpgsqlCommand(sql, con);
foreach (var item in outstanding)
{
cmd.Parameters.AddWithValue("name",item);
cmd.Prepare();
cmd.ExecuteNonQuery();
}
What did I miss? TYIA
8 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Jona4Play
Jona4Play2y ago
This might be true but your suggested change below for testing didn't work either. Prepare() seems to be a command to speed up future repetitions of a command by holding it in cache and just waiting the value from the program and not the whole string.
Jona4Play
Jona4Play2y ago
Here is a picture of what the DB looks like as it might be a bit unclear because of my description. The List I provided consisted of 6 unique links
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Jona4Play
Jona4Play2y ago
You're right. This works. But still a bit weird I feel. Anyways, huge thanks for saving me a ton of time. Have a lovely day 😄
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Jona4Play
Jona4Play2y ago
Nice. Thank you
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity. Closed!
Want results from more Discord servers?
Add your server
More Posts