I'm declaring some variables then
I'm looping through some data using switch command if an attribute exists it gets assigned to the relevant variable It is possible age will not be found the PostgreSQL Table reflects this
CREATE my_table(
id SERIAL PRIMARY KEY,
name varchar,
age INTEGER
);
The code snippet is giving me errors
- Use of unassigned local variable 'age'
- Argument 2: cannot convert from 'out int?' to 'out int'
- Cannot convert type 'System.DBNull' to 'int'
How do I declare a null int and maybe assign a value if not pass it to the database as null?
IN pseudo code to show the gist of what I'm doing
// declared at the same level
string name = string.Empty;
int? age;
foreach (var p in Feature.Properties)
{
var Key = p.Key;
var Value = p.Value;
switch (Key.ToLower())
{
case "name":
{
name = Value;
break;
}
case "age":
{
// May not exist
// Err 2
int.TryParse(Value, out age);
break;
}
}
}
// Err 1 name is OK
Console.WriteLine(name + age);
using (var DB_con = new NpgsqlConnection(cs))
{
var sql = "INSERT INTO my_table (name,age )VALUES "+
"(@p_name, @p_age RETURNING id;";
using (var cmd = new NpgsqlCommand(sql, DB_con))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("@p_name", name);
// Err 3
cmd.Parameters.AddWithValue("@p_age", age ?? (int)DBNull.Value );
DB_con.Open();
var res = cmd.ExecuteScalar();
DB_con.Close();
}
}