Skip to content

Instantly share code, notes, and snippets.

@jbubriski
Last active December 18, 2015 07:59
Show Gist options
  • Save jbubriski/5750708 to your computer and use it in GitHub Desktop.
Save jbubriski/5750708 to your computer and use it in GitHub Desktop.
Executing queries with SqlConnection and SqlCommand.
public void NonQuery()
{
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
var sqlCommandText = "UPDATE People SET Name = 'John'";
using (var sqlConnection = new SqlConnection(connectionString))
using (var sqlCommand = new SqlCommand(sqlCommandText, sqlConnection))
{
sqlCommand.Connection.Open();
sqlCommand.ExecuteNonQuery();
sqlCommand.Connection.Close();
}
}
public void Query()
{
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
var sqlCommandText = "SELECT FirstName FROM People WHERE LastName = @LastName";
using (var sqlConnection = new SqlConnection(connectionString))
using (var sqlCommand = new SqlCommand(sqlCommandText, sqlConnection))
{
sqlCommand.Parameters.AddWithValue("LastName", "Bubriski");
sqlCommand.Connection.Open();
using(var sqlReader = sqlCommand.ExecuteReader())
{
while(sqlReader.Read())
{
// Do something with the data
var firstName = sqlReader["FirstName"];
}
}
sqlCommand.Connection.Close();
}
}
public DataSet QueryDataSet()
{
var dataSet = new DataSet();
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
var sqlCommandText = "SELECT FirstName FROM People WHERE LastName = @LastName";
using (var sqlConnection = new SqlConnection(connectionString))
using (var sqlCommand = new SqlCommand(sqlCommandText, sqlConnection))
{
sqlCommand.Parameters.AddWithValue("LastName", "Bubriski");
sqlCommand.Connection.Open();
using (var sqlDataAdapter = new SqlDataAdapter(sqlCommand))
{
sqlDataAdapter.Fill(dataSet);
}
sqlCommand.Connection.Close();
}
return dataSet;
}
public int Scalar()
{
var peopleCount = 0;
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
var sqlCommandText = "SELECT COUNT(*) FROM People";
using (var sqlConnection = new SqlConnection(connectionString))
using (var sqlCommand = new SqlCommand(sqlCommandText, sqlConnection))
{
sqlCommand.Connection.Open();
peopleCount = sqlCommand.ExecuteScalar();
sqlCommand.Connection.Close();
}
return peopleCount;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment