Skip to content

Instantly share code, notes, and snippets.

@greggnakamura
Forked from jbubriski/NonQuery.cs
Created June 10, 2013 17:53
Show Gist options
  • Save greggnakamura/5750830 to your computer and use it in GitHub Desktop.
Save greggnakamura/5750830 to your computer and use it in GitHub Desktop.
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