Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
Project SQL
Purpose
The purpose of this tutorial is to show how to use different SQL commands (to interact with a SQL database) using C# .Net 4.6. These examples are by no means the only commands but those which have been found to be used the most when the ability to call stored procedures is not an option. Calling stored procedures is the safest method, however.

Database Insert/Update:

strQuery = "INSERT INTO dbo.mydatabase (description) VALUES (@description);";
strConnection = "ConfigurationManager.ConnectionStrings["connection-string-info-in-web-config"].ConnectionString;
using (SqlConnection connection = new SqlConnection(strConnection))
{
	SqlCommand command = new SqlCommand(strQuery, connection);
	command.Parameters.AddWithValue("@description", "some numeric or string value to add");

	command.Connection.Open();
	command.ExecuteNonQuery();
	command.Connection.Close();
}


Database Query:

strQuery = "SELECT * FROM dbo.mydatabase WHERE description = @description;";
strConnection = "ConfigurationManager.ConnectionStrings["connection-string-info-in-web-config"].ConnectionString;
SqlConnection sqlConnection1 = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand(strQuery);
var tmp_description = new SqlParameter("description", SqlDbType.VarChar);
tmp_description.Value = "some string value";
cmd.Parameters.Add(tmp_description);
cmd.Connection = sqlConnection1;

sqlConnection1.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) {
	var result = reader[0].ToString();
}
sqlConnection1.Close();


About Joe