【发布时间】:2021-08-30 09:31:56
【问题描述】:
然后我声明一些变量
如果存在属性,我将使用 switch 命令遍历一些数据,它会被分配给相关变量 可能找不到年龄,PostgreSQL 表反映了这一点
CREATE my_table(
id SERIAL PRIMARY KEY,
name varchar,
age INTEGER
);
代码 sn-p 给了我错误
- 使用未赋值的局部变量“age”
- 参数 2:无法从“out int”转换?到'out int'
- 无法将类型“System.DBNull”转换为“int”
我如何声明一个 null int,如果不将它作为 null 传递给数据库,则可能分配一个值?
IN 伪代码显示我正在做的事情的要点
// 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();
}
}
【问题讨论】:
-
1) -
int? age = default;或int? age = null; -
3) Parameter.Value 的类型为
object,因此应为(object) age ?? DBNull.Value。不要尝试将 DBNull.Value 转换为 int,因为这是无效的。 -
谢谢 stuartd 和 Igor,你们的 cmets 解决了问题
-
Age 是派生值,改为存储 Birthdate。
标签: c# .net postgresql