SQL Server With CSharp WinForms
SQL Server With CSharp WinForms
blog
SQL Server
Hans-Petter Halvorsen
What is a Database?
• A Database is a structured way to store lots of information.
• The information inside the database is stored in different
tables.
• - “Everything” today is stored in databases!
Examples:
• Bank/Account systems
• Information in Web pages such as Facebook, Wikipedia,
YouTube, etc.
• … lots of other examples!
Database Systems
We communicate with the Database using a Database Management
System (DBMS). We use the Structured Query Language (SQL) in
order to communicate with the Database, i.e., Insert Data, Retrieve
Data, Update Data and Delete Data from the Database.
Database
Management
System SQL Database
(DBMS)
Your
Tables
ADO.NET
Hans-Petter Halvorsen
ADO.NET
• ADO.NET is the core data access
technology for .NET languages.
• System.Data.SqlClient (or the newer
Microsoft.Data.SqlClient) is the
provider or namespace you typically
use to connect to an SQL Server
Installation in Visual Studio
• Typically, we need to add the necessary
NuGet package for that
• NuGet is the package manager for .NET
• The NuGet client tools provide the
ability to produce and consume
packages
https://www.halvorsen.blog
Hans-Petter Halvorsen
Windows Forms App
https://www.halvorsen.blog
Basic Example
Hans-Petter Halvorsen
Basic Example
Basic Example
• Sensor Type
–Temperature, Pressure, ..
• Sensor Name
Database
Code
using Microsoft.Data.SqlClient;
using System.Windows.Forms;
namespace SensorSystem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
con.Open();
SqlCommand sc = new SqlCommand(sqlQuery, con);
sc.ExecuteNonQuery();
con.Close();
}
}
}
Running the Application
App.config
Hans-Petter Halvorsen
Use App.config
<connectionStrings>
<add name="DatabaseConnectionString" connectionString="Data Source=x;Initial Catalog=x;Trusted_Connection=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Code
using System;
using Microsoft.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;
namespace SensorSystem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
con.Open();
SqlCommand sc = new SqlCommand(sqlQuery, con);
sc.ExecuteNonQuery();
con.Close();
}
}
}
https://www.halvorsen.blog
SQL Parameters
Hans-Petter Halvorsen
Use SQL Parameters
• Using SQL Parameters are safer than putting the
values into the string because the parameters are
passed to the database separately, protecting
against SQL injection attacks.
• It is also be more efficient if you execute the
same SQL repeatedly with different parameters.
• The Example is showing Windows Forms using C#
• Other Languages like PHP, Python, etc. offer the
same functionality
using System;
Code
using Microsoft.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;
namespace SensorSystem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
cmd.ExecuteNonQuery();
con.Close();
}
}
}
https://www.halvorsen.blog
Stored Procedure
Hans-Petter Halvorsen
Use Stored Procedure
• A Stored Procedure is a premade SQL
Script which you can use inside your
C# Code
• Here you also use SQL Parameters
• Using Stored Procedure and SQL
Parameters prevent SQL Injection
Stored Procedure
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = 'SaveSensor'
AND type = 'P')
DROP PROCEDURE SaveSensor
GO
GO
using System;
using System.Data;
using Microsoft.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;
namespace SensorSystem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
cmd.ExecuteNonQuery();
con.Close();
}
}
}
https://www.halvorsen.blog
Try .. Catch ..
Hans-Petter Halvorsen
Use Try … Catch
• When executing C# code, different
errors may occur
• When an error occurs, C# will normally
stop and generate an error message.
• Typically, we just want to show an Error
Message to the user without stopping
the application
• Then we can use Try … Catch
Try … Catch
try
{
// Put your ordinary Code here
}
catch (Exception ex)
{
// Code for Handling Errors
}
Code
private void btnSave_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
try
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Error Writing Data to Database");
}
}
https://www.halvorsen.blog
Hans-Petter Halvorsen
Create Classes and Methods
• So far, we have used the Button Click
Event Method
btnSave_Click()and then we
created all code inside that Method
• Better to create separate Classes and
Methods
Create a Separate Method
private void btnSave_Click(object sender, EventArgs e)
{
SaveData();
}
try
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Error Writing Data to Database");
}
}
Create a Class and Method
using
Create a Class and Method
System.Data;
using System.Windows.Forms;
using Microsoft.Data.SqlClient;
using System.Configuration;
namespace SensorSystem.Classes
{
class Sensor
{
public void SaveSensorData(string sensorName, string sensorType)
{
string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
try
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Error Writing Data to Database");
}
}
}
}
Using the Class and Method
using System;
using System.Windows.Forms;
using SensorSystem.Classes;
namespace SensorSystem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
sensor.SaveSensorData(sensorName, sensorType);
}
}
}
https://www.halvorsen.blog
Improve Database
Hans-Petter Halvorsen
Updated Database
CREATE TABLE SENSOR_TYPE
(
SensorTypeId int PRIMARY KEY IDENTITY (1,1),
SensorType varchar(50) NOT NULL UNIQUE
)
GO
DECLARE
@SensorTypeId int
GO
Updated GUI
Sensor Types are now a Drop-down List. This
prevent you from spelling mistakes, and getting
Sensor Types like “Temperature”, “Tmperature”, ..
SqlDataReader dr = cmd.ExecuteReader();
if (dr != null)
{
while (dr.Read())
{
SensorType sensorType = new SensorType();
sensorType.SensorTypeId = Convert.ToInt32(dr["SensorTypeId"]);
sensorType.SensorTypeName = dr["SensorType"].ToString();
sensorTypeList.Add(sensorType);
}
}
con.Close();
return sensorTypeList;
}
}
}
using System.Data;
using System.Windows.Forms;
using
using
Microsoft.Data.SqlClient;
System.Configuration;
Sensor.cs
namespace SensorSystem.Classes
{
class Sensor
{
string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Error Writing Data to Database");
}
}
}
}
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using SensorSystem.Classes; Form1.cs
namespace SensorSystem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FillSensorTypeComboBox();
}
sensorTypeList = sensorType.GetSensorTypes();
E-mail: [email protected]
Web: https://www.halvorsen.blog