Database connection : C# with Database

Now we are going to insert information in database.

Consider this window,

Now take a class named StudentMark :
class StudentMark
  private string studentRoll;
  private string bangla;
  private string english;
  private string math;
  public string StudentRoll
    get { return studentRoll; }
    set { studentRoll = value; }
  public string Bangla
    get { return bangla; }
    set { bangla = value; }
  public string English
   get { return english; }
   set { english = value; }
  public string Math
   get { return math; }
   set { math = value; }
Now double click on SAVE BUTTON :
private void saveButton_Click(object sender, EventArgs e)
 StudentMark studentData = new StudentMark();
 studentData.StudentRoll = studentRollTextBox.Text;
 studentData.Bangla = banglaTextBox.Text;
 studentData.English = englishTextBox.Text;
 studentData.Math = mathTextBox.Text;
 MessageBox.Show(“Information has been saved.”);
 Gateway gateway = new Gateway();
Now we can save data normally by running this code. Now we want to connect it with SQL server and save data in it.
Now open SQL server 2008 and create new database. Give database name and click add button.Let our database name is Mark.
Now create a table named t_Mark just like this,
Now click OK button .
Now close the SQL server window and again open Visual Studio 2008 and open our StudentNumber program.
Now we have to create another class named Gateway.cs to get connection with SQL server.
Click view menu and go to Server Explorer.
Now click “Connect to Database”.
Then we will see this,
 Then write our server name and then select our Database name from combo box. Now we can see our database under Data Connections.
Now create a class named Gateway.cs  :
class Gateway
 public bool Save(StudentMark student)
 string connectionString = @”Here write our own Data Source”;
 SqlConnection connection = new SqlConnection(connectionString);
 string query = @”insert into t_Mark values (‘” + student.StudentRoll + “‘,'” + student.Bangla + “‘,'” +     student.English + “‘,'” + student.Math + “‘)”;
 SqlCommand command = new SqlCommand(query, connection);
 return true;
Now if we run our program and give inputs,
Then open our database t_Mark table and we can see,
So this program can take inputs and can insert our data into Database.

Leave a Reply