Retrive Email of a User using Id in C# and SQL Server
Code in C# to retrive email address of a User with given id.
You can use @
to avoid special characters in string
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 System.Data.SqlClient;
namespace DatabaseApp
{
public partial class Form1 : Form
{
// SQL Connection
SqlConnection scon = new SqlConnection(@"Data Source=DESKTOP-OKJGB88\SQLEXPRESS;Initial Catalog=bscs;Integrated Security=True");
private SqlCommand scom;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Write a SQL command for retriving email of given id
scom = new SqlCommand("Select email from Contacts WHERE id=@id", scon);
scom.Parameters.AddWithValue("@id", 2);
scon.Open();
String email = scom.ExecuteScalar().ToString();
MessageBox.Show("Email is: " + email);
}
}
}
No comments