-
Notifications
You must be signed in to change notification settings - Fork 0
/
DatabaseOperations.cs
66 lines (61 loc) · 2.32 KB
/
DatabaseOperations.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Npgsql;
namespace sqltest
{
public class DatabaseOperations
{
private string connectionString = "Host=localhost;Username=postgres;Password=password;Database=postgres";
public async Task CreateTablesAsync()
{
try
{
// List of CREATE TABLE statements
var statements = new List<string>
{
@"
CREATE TABLE IF NOT EXISTS courses (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL UNIQUE,
duration INTERVAL NOT NULL,
description TEXT,
credits INT
)",
@"
CREATE TABLE IF NOT EXISTS students (
id SERIAL PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email VARCHAR(400) NOT NULL UNIQUE,
registration_date DATE NOT NULL
)",
@"
CREATE TABLE IF NOT EXISTS enrollments (
student_id INT NOT NULL,
course_id INT NOT NULL,
enrolled_date DATE NOT NULL,
PRIMARY KEY(student_id, course_id),
FOREIGN KEY(student_id) REFERENCES students(id),
FOREIGN KEY(course_id) REFERENCES courses(id)
)"
};
await using var dataSource = NpgsqlDataSource.Create(connectionString);
foreach (var statement in statements)
{
await using var cmd = dataSource.CreateCommand(statement);
await cmd.ExecuteNonQueryAsync();
}
Console.WriteLine("The tables have been created successfully.");
}
catch (NpgsqlException ex)
{
Console.WriteLine($"Database error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
}