Вы не показали нам много кода, но я дам вам хороший пример того, как я управляю связью между программой и базой данных SQL.
Итак, прежде всего я создаю класс для каждого объекта. В вашем примере я вижу, что у вас есть Employee
, поэтому я бы создал класс с небольшим количеством информации (переменных) о каждом из моих сотрудников и функциях, которые я хочу иметь для них. Итак, класс будет выглядеть примерно так:
public class Employee
{
static string databaseString = "";
public int Id { get { return _Id; } } //This is property
public string Name { get { return _Name; } set { _Name = value; } } //This is property
private int _Id; //This is private variable used by property
private string _Name; //This is private variable used by property
public Employee()
{
//Constructor used to create empty object
}
public Employee(int Id)
{
try
{
using (SqlConnection con = new SqlConnection(databaseString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT NAME FROM Employee WHERE ID = @ID", con))
{
cmd.Parameters.AddWithValue("@ID", Id);
SqlDataReader dr = cmd.ExecuteReader();
//I am usin IF(dr.Read()) instead of WHILE(dr.Read()) since i want to read only first row.
if (dr.Read())
{
this._Id = Id;
this._Name = dr[0].ToString();
}
else
{
System.Windows.Forms.MessageBox.Show("There was no Employee with that ID in database!");
}
}
}
}
catch(SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}
public void Save(bool showMessage)
{
using (SqlConnection con = new SqlConnection(databaseString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE Employee SET NAME = @N WHERE ID = @ID", con))
{
cmd.Parameters.AddWithValue("@N", this._Name);
cmd.Parameters.AddWithValue("@ID", this._Id);
cmd.ExecuteNonQuery();
if (showMessage)
System.Windows.Forms.MessageBox.Show("Employee saved!");
}
}
}
public static void Create(string Name, bool showMessage = true)
{
using (SqlConnection con = new SqlConnection(databaseString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Employee (ID, NAME) VALUES (COALESCE(MAX(ID), 1), @NAME)", con))
{
cmd.ExecuteNonQuery();
if (showMessage)
System.Windows.Forms.MessageBox.Show("New Employee created!");
}
}
}
}
Теперь, когда у меня есть класс, я могу назвать его двумя способами:
Employee emp = new Employee(); //This will create empty employee object
Employee emp1 = new Employee(1); //This will create employee object and will load employees data from database where employees id == 1
Также я могу сделать следующее:
Employee.Create("SomeName"); //Calling public static method from Employee class. Doesn't require you to create object for static methods
или если я загрузил сотрудника и хочу изменить его имя, а затем сохранить, я бы сделал это так:
Employee emp2 = new Employee(1); //Created and loaded emp from database
emp2.Name = "Changed Name";
emp2.Save(); //Called public method.
Так что теперь, если у вас есть форма с одним сотрудником, она будет выглядеть так:
public partial class Form1 : Form
{
private Employee emp;
public Form(int EmployeeID)
{
InitializeComponents();
//Creating new object of Employee but with constructor that will automatically load variables into it.
emp = new Employee(EmployeeID);
//Checking to see if employee is loaded since if there was no employee with given ID it would return null
if(emp.Id == null || < 1)
{
DialogResult dr = MessageBox.Show("Employee doesn't exist. Do you want to create new one?", "Confirm", MessageBoxButtons.YesNo);
if(dr == DialogResult.No)
{
//User doesn't want to create new employee but since there is no employee loaded we close form
this.Close();
}
else
{
Employee.Create("New Employee");
MessageBox.Show("New employee created");
//Here we need to load this employee with code like emp = new Employee(newEmployeeId);
//To get new employee id you have 2 options. First is to create function inside Employee class that will Select MAX(ID) from Employee and return it. (bad solution)
//Second solution is to return value upon creating new employee so instead function `public static void Create()` you need to have `public static int Create()` so it returns newly created ID of new row in SQL database. I won't explain it since you are new and it will be too much information for now. You will easily improve code later. For now you can use Select Max(id) method
}
}
textBox1.Text = emp.Id;
textBox2.Text = emp.Name;
}
private void OnButton_Save_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("Do you really want to save changes?", "Save", MessageBoxButtons.YesNo);
if(dr == DialogResult.Yes)
{
emp.Save();
}
else
{
//Here create private Reload function inside form that will do emp = Employee(emp.Id) and then set UI again.
}
}
private void OnButton_CreateNewEmployee_Click(object sender, EventArgs e)
{
Employee.Create("New Employee");
int newEmpID = something; //As i said up create method to select MAX ID or update SQL inside Create function to return newly created ID
//I am using using since after form closes it automatically disposes it
using(Form1 f = new Form1(newEmpID))
{
f.showDialog()
}
this.Close();
}
}