C# pgsql中如何處理日期和時(shí)間類型

c#
小樊
93
2024-08-22 05:33:32
欄目: 云計(jì)算

在C#中處理日期和時(shí)間類型時(shí),可以使用DateTime類來(lái)表示日期和時(shí)間。而在操作PostgreSQL數(shù)據(jù)庫(kù)時(shí),可以將日期和時(shí)間類型映射為C#中的DateTime類型。

在從數(shù)據(jù)庫(kù)中讀取日期和時(shí)間類型數(shù)據(jù)時(shí),可以使用DateTime.Parse()方法將其轉(zhuǎn)換為DateTime類型,例如:

using System;
using Npgsql;

class Program
{
    static void Main()
    {
        string connString = "Host=localhost;Username=myuser;Password=mypassword;Database=mydatabase";
        using (var conn = new NpgsqlConnection(connString))
        {
            conn.Open();
            using (var cmd = new NpgsqlCommand("SELECT birthdate FROM users WHERE id = 1", conn))
            {
                DateTime birthDate = DateTime.Parse(cmd.ExecuteScalar().ToString());
                Console.WriteLine("Birthdate: " + birthDate);
            }
        }
    }
}

在向數(shù)據(jù)庫(kù)中插入日期和時(shí)間類型數(shù)據(jù)時(shí),可以直接將DateTime類型賦給參數(shù),例如:

using System;
using Npgsql;

class Program
{
    static void Main()
    {
        string connString = "Host=localhost;Username=myuser;Password=mypassword;Database=mydatabase";
        using (var conn = new NpgsqlConnection(connString))
        {
            conn.Open();
            using (var cmd = new NpgsqlCommand("INSERT INTO users (name, birthdate) VALUES (@name, @birthdate)", conn))
            {
                cmd.Parameters.AddWithValue("name", "Alice");
                cmd.Parameters.AddWithValue("birthdate", DateTime.Now);
                cmd.ExecuteNonQuery();
            }
        }
    }
}

這樣就可以在C#中處理PostgreSQL數(shù)據(jù)庫(kù)中的日期和時(shí)間類型數(shù)據(jù)。

0