Файл: Факультет автоматики и вычислительной техники кафедра вычислительной техники.docx

ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 03.02.2024

Просмотров: 8

Скачиваний: 1

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ

ФЕДЕРАЛЬНОЕ государственное БЮДЖЕТНОЕ

образовательное учреждение

высшего образования

«НОВОСИБИРСКИЙ ГОСУДАРСТВЕННЫЙ ТЕХНИЧЕСКИЙ УНИВЕРСИТЕТ»

__________________________________________________________________

ФАКУЛЬТЕТ АВТОМАТИКИ И ВЫЧИСЛИТЕЛЬНОЙ ТЕХНИКИ

КАФЕДРА ВЫЧИСЛИТЕЛЬНОЙ ТЕХНИКИ



Лабораторная работа №1-2

по дисциплине «Информационные системы»

Факультет: АВТФ

Группа: АВТ-018

Выполнил: Мартай-оол А.А.

Преподаватель: Дубков И.С.

Цель работы

Создать проект, в котором будет использована библиотека Ngpsql. В проекте должны быть кнопки, текстовые поля и один label. С помощью библиотеки соединить между сервером pgAdmin и проектом. Вывести таблицу.

Ход работы



Рис. 1 – Form1.

Создали 4 кнопки, 5 текстовых полей и один label:

  • 1 кнопка для инициализации соединения;

  • 2 - 3 кнопка для открытия и закрытия соединения;

  • 4 кнопка для выполнения команды, выведение таблицы.

  • текстовые поля служат для введения названия сервера, порта, названия пользователя, пароль, название базы данных;

  • label – служит для показа состояния соединения.

Код подключения библиотеки

using Npgsql;

...

private string connstring = String.Format("Server={0};Port={1};" + "Username={2};Password={3};Database={4};",

"localhost", 5432, "postgres", "postgres", "Cars");

private NpgsqlConnection conn;

public Form1()

{

InitializeComponent();

}
private void Form1_Load(object sender, EventArgs e)

{

conn = new NpgsqlConnection(connstring);

}



Код создания Form1

private void button1_Click(object sender, EventArgs e)

{

if ((textBox1.Text == "localhost") && (textBox2.Text == "5432") && (textBox3.Text == "postgres") && (textBox4.Text == "postgres") && (textBox5.Text == "Cars"))

{

MessageBox.Show("Инициализация соединения прошла успешна");

button2.Enabled = true;

textBox1.Enabled = false;

textBox2.Enabled = false;

textBox3.Enabled = false;

textBox4.Enabled = false;

textBox5.Enabled = false;

}

else MessageBox.Show("Инициализация соединения не прошла");

}

private void button2_Click(object sender, EventArgs e)

{

conn.Open();

label5.Text = "Соединения открыто";

button3.Enabled = true;

button4.Enabled = true;

button2.Enabled = false;

}

private void button3_Click(object sender, EventArgs e)

{

conn.Close();

label5.Text = "Соединения закрыто";

button2.Enabled = true;

button4.Enabled = false;

button3.Enabled = false;

}
private void button4_Click(object sender, EventArgs e)

{

Form2 form = new Form2();

form.Show();

}


При нажатий кнопки «выполнить команду», открывается другая форма. При успешном соединений выведет таблица. Иначе выведет ошибку.

Код для выведения таблицы

private void Form2_Load(object sender, EventArgs e)

{

conn = new NpgsqlConnection(connstring);

Select();

}
private void Select()

{

try

{

if (conn.State != ConnectionState.Open) conn.Open();

sql = @"SELECT * FROM car_select();";

cmd = new NpgsqlCommand(sql, conn);

dt = new DataTable();

dt.Load(cmd.ExecuteReader());

conn.Close();

dataGridView1.DataSource = null;

dataGridView1.DataSource = dt;

}

catch (Exception ex)

{

conn.Close();

MessageBox.Show("Error: "+ex.Message);

}

}



Для выведения таблицы используется созданная ранее функция в pgAdmin “car_select”. Сама функция создана так:

Create or replace Function car_select() returns table (

s_id integer,

s_name character varying,

s_year integer,

s_price integer,

s_mileage integer

)

as $$

begin

return query

select id, name, year, price, mileage from car_info order by id;

end $$

language plpgsql;



Рис. 2 Form2.

Как видим, соединение прошла успешно. Таблица выведена на dataGridView.

Приложение

Form1

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using Npgsql;
namespace LR

{

public partial class Form1 : Form

{

private string connstring = String.Format(“Server={0};Port={1};” + “Username={2};Password={3};Database={4};”,

“localhost”, 5432, “postgres”, “postgres”, “Cars”);

private NpgsqlConnection conn;
public Form1()

{

InitializeComponent();

}
private void Form1_Load(object sender, EventArgs e)

{

conn = new NpgsqlConnection(connstring);

}
private void button1_Click(object sender, EventArgs e)

{

if ((textBox1.Text == “localhost”) && (textBox2.Text == “5432”) && (textBox3.Text == “postgres”) && (textBox4.Text == “postgres”) && (textBox5.Text == “Cars”))

{

MessageBox.Show(«Инициализация соединения прошла успешна»);

button2.Enabled = true;

textBox1.Enabled = false;

textBox2.Enabled = false;

textBox3.Enabled = false;

textBox4.Enabled = false;

textBox5.Enabled = false;

}

else MessageBox.Show(«Инициализация соединения не прошла»);

}

private void button2_Click(object sender, EventArgs e)

{

conn.Open();

label5.Text = «Соединения открыто»;

button3.Enabled = true;

button4.Enabled = true;

button2.Enabled = false;

}

private void button3_Click(object sender, EventArgs e)

{

conn.Close();

label5.Text = «Соединения закрыто»;

button2.Enabled = true;

button4.Enabled = false;

button3.Enabled = false;

}
private void button4_Click(object sender, EventArgs e)

{

Form2 form = new Form2();

form.Show();

}

}

}

Form2

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;



using System.Text;

using System.Windows.Forms;

using Npgsql;
namespace LR

{

public partial class Form2 : Form

{

private string connstring = String.Format("Server={0};Port={1};" + "Username={2};Password={3};Database={4};",

"localhost", 5432, "postgres", "postgres", "Cars");

private NpgsqlConnection conn;

private string sql;

private NpgsqlCommand cmd;

private DataTable dt;

private int rowIndex = -1;

public Form2()

{

InitializeComponent();

}
private void Form2_Load(object sender, EventArgs e)

{

conn = new NpgsqlConnection(connstring);

Select();

}
private void Select()

{

try

{

if (conn.State != ConnectionState.Open) conn.Open();

sql = @"SELECT * FROM car_select();";

cmd = new NpgsqlCommand(sql, conn);

dt = new DataTable();

dt.Load(cmd.ExecuteReader());

conn.Close();

dataGridView1.DataSource = null;

dataGridView1.DataSource = dt;

}

catch (Exception ex)

{

conn.Close();

MessageBox.Show("Error: "+ex.Message);

}

}


private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)

{

if (e.RowIndex >= 0)

{

rowIndex = e.RowIndex;

textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells["s_name"].Value.ToString();

textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells["s_year"].Value.ToString();

textBox3.Text = dataGridView1.Rows[e.RowIndex].Cells["s_price"].Value.ToString();

textBox4.Text = dataGridView1.Rows[e.RowIndex].Cells["s_mileage"].Value.ToString();

}

}
private void button1_Click(object sender, EventArgs e)

{

rowIndex = -1;

textBox1.Enabled = textBox2.Enabled = textBox3.Enabled = textBox4.Enabled = true;

textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = null;

textBox1.Select();

}
private void button2_Click(object sender, EventArgs e)

{

if (rowIndex < 0)

{

MessageBox.Show("Please choose student to update");

return;

}

textBox1.Enabled = textBox2.Enabled = textBox3.Enabled = textBox4.Enabled = true;

}
private void button3_Click(object sender, EventArgs e)

{

if (rowIndex < 0)

{

MessageBox.Show("Please choose student to delete");

return;

}

try

{

if (conn.State != ConnectionState.Open) conn.Open();

sql = @"Select * from car_delete(:_id)";

cmd = new NpgsqlCommand(sql, conn);

cmd.Parameters.AddWithValue("_id", int.Parse(dataGridView1.Rows[rowIndex].Cells["s_id"].Value.ToString()));

if ((int)cmd.ExecuteScalar() == 1)

{

MessageBox.Show("Delete student succeccfully");

rowIndex = -1;

Select();

}

conn.Close();

}

catch (Exception ex)

{

conn.Close();

MessageBox.Show("Delete fail. Error: "+ex.Message);

}

}
private void button5_Click(object sender, EventArgs e)

{

int result = 0;

if (rowIndex < 0)

{

try

{

if (conn.State != ConnectionState.Open) conn.Open();

sql = @"Select * from car_insert(:_name, :_year, :_price, :_mileage)";

cmd = new NpgsqlCommand(sql, conn);

cmd.Parameters.AddWithValue("_name", textBox1.Text);

cmd.Parameters.AddWithValue("_year", int.Parse(textBox2.Text));

cmd.Parameters.AddWithValue("_price", int.Parse(textBox3.Text));

cmd.Parameters.AddWithValue("_mileage", int.Parse(textBox4.Text));

result = (int)cmd.ExecuteScalar();

conn.Close();

if (result == 1)

{

MessageBox.Show("Inserted successfully");

Select();

}

else

{

MessageBox.Show("Inserted fail");

}

}

catch (Exception ex)

{

conn.Close();

MessageBox.Show("Inserted fail. Error: " + ex.Message);

}

}

else

{

try

{

if (conn.State != ConnectionState.Open) conn.Open();

sql = @"Select * from car_update(:_id, :_name, :_year, :_price, :_mileage)";

cmd = new NpgsqlCommand(sql, conn);

cmd.Parameters.AddWithValue("_id", int.Parse(dataGridView1.Rows[rowIndex].Cells["s_id"].Value.ToString()));

cmd.Parameters.AddWithValue("_name", textBox1.Text);


cmd.Parameters.AddWithValue("_year", int.Parse(textBox2.Text));

cmd.Parameters.AddWithValue("_price", int.Parse(textBox3.Text));

cmd.Parameters.AddWithValue("_mileage", int.Parse(textBox4.Text));

result = (int)cmd.ExecuteScalar();

conn.Close();

if (result == 1)

{

MessageBox.Show("Updated successfully");

Select();

}

else

{

MessageBox.Show("Updated fail");

}

}

catch (Exception ex)

{

conn.Close();

MessageBox.Show("Updated fail. Error: " + ex.Message);

}

}

result = 0;

textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = null;

textBox1.Enabled = textBox2.Enabled = textBox3.Enabled = textBox4.Enabled = false;

}

}

}

Новосибирск

2022