using System;
using System.Data.SqlClient;
class FirstExample
{
public static void Main()
{
try
{
SqlConnection mySqlConnection = new SqlConnection("server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI");
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "SELECT id, firstname, lastname from employee";
mySqlConnection.Open();
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
mySqlDataReader.Read();
Console.WriteLine("mySqlDataReader[" ID"] = "+ mySqlDataReader["ID"]);
Console.WriteLine("mySqlDataReader[" First Name"] = "+ mySqlDataReader["FirstName"]);
Console.WriteLine("mySqlDataReader[" Last Name"] = "+ mySqlDataReader["LastName"]);
mySqlDataReader.Close();
mySqlConnection.Close();
}
catch (SqlException e)
{
Console.WriteLine("A SqlException was thrown");
Console.WriteLine("Number = "+ e.Number);
Console.WriteLine("Message = "+ e.Message);
Console.WriteLine("StackTrace:
" + e.StackTrace);
}
}
}
Month: February 2011
Read column values as C# types using the 'Get' methods
using System;
using System.Data;
using System.Data.SqlClient;
class StronglyTypedColumnValues
{
public static void Main()
{
SqlConnection mySqlConnection =new SqlConnection("server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName, UnitPrice, " +
"UnitsInStock, Discontinued " +
"FROM Products " +
"ORDER BY ProductID";
mySqlConnection.Open();
SqlDataReader productsSqlDataReader = mySqlCommand.ExecuteReader();
int productIDColPos = productsSqlDataReader.GetOrdinal("ProductID");
int productNameColPos = productsSqlDataReader.GetOrdinal("ProductName");
int unitPriceColPos = productsSqlDataReader.GetOrdinal("UnitPrice");
int unitsInStockColPos = productsSqlDataReader.GetOrdinal("UnitsInStock");
int discontinuedColPos = productsSqlDataReader.GetOrdinal("Discontinued");
Console.WriteLine("ProductID .NET type = " + productsSqlDataReader.GetFieldType(productIDColPos));
Console.WriteLine("ProductName .NET type = " + productsSqlDataReader.GetFieldType(productNameColPos));
Console.WriteLine("UnitPrice .NET type = " + productsSqlDataReader.GetFieldType(unitPriceColPos));
Console.WriteLine("UnitsInStock .NET type = " + productsSqlDataReader.GetFieldType(unitsInStockColPos));
Console.WriteLine("Discontinued .NET type = " + productsSqlDataReader.GetFieldType(discontinuedColPos));
Console.WriteLine("ProductID database type = " + productsSqlDataReader.GetDataTypeName(productIDColPos));
Console.WriteLine("ProductName database type = " + productsSqlDataReader.GetDataTypeName(productNameColPos));
Console.WriteLine("UnitPrice database type = " + productsSqlDataReader.GetDataTypeName(unitPriceColPos));
Console.WriteLine("UnitsInStock database type = " + productsSqlDataReader.GetDataTypeName(unitsInStockColPos));
Console.WriteLine("Discontinued database type = " + productsSqlDataReader.GetDataTypeName(discontinuedColPos));
while (productsSqlDataReader.Read())
{
int productID = productsSqlDataReader.GetInt32(productIDColPos);
Console.WriteLine("productID = " + productID);
string productName = productsSqlDataReader.GetString(productNameColPos);
Console.WriteLine("productName = " + productName);
decimal unitPrice = productsSqlDataReader.GetDecimal(unitPriceColPos);
Console.WriteLine("unitPrice = " + unitPrice);
short unitsInStock = productsSqlDataReader.GetInt16(unitsInStockColPos);
Console.WriteLine("unitsInStock = " + unitsInStock);
bool discontinued = productsSqlDataReader.GetBoolean(discontinuedColPos);
Console.WriteLine("discontinued = " + discontinued);
}
productsSqlDataReader.Close();
mySqlConnection.Close();
}
}
Geting Table column data type
using System;
using System.Data;
using System.Data.OleDb;
public class DatabaseInfo {
public static void Main () {
String connect = "Provider=Microsoft.JET.OLEDB.4.0;data source=.Employee.mdb";
OleDbConnection con = new OleDbConnection(connect);
con.Open();
Console.WriteLine("Made the connection to the database");
Console.WriteLine("Information for each table contains:");
DataTable tables = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"TABLE"});
foreach(DataColumn col in tables.Columns)
Console.WriteLine("{0} {1}", col.ColumnName, col.DataType);
con.Close();
}
}
Call a store procedure
//Call a store procedure
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
* Version: 1
*/
using System;
using System.Data;
using System.Data.SqlClient;
namespace Client.Chapter_13___ADO.NET
{
public class Callastoreprocedure
{
static void Main(string[] args)
{
SqlConnection cn = new SqlConnection(
"Data Source=(local); Initial Catalog = MyDatabase; User ID=sa;Password=");
SqlCommand cmd = new SqlCommand("MyStoredProcedure", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("@ReturnValue", SqlDbType.Int);
cmd.Parameters.Add(param);
cmd.Parameters.Add("MyFirstParameter", SqlDbType.Int);
cmd.Parameters.Add("MySecondParameter", SqlDbType.Int).Direction =
ParameterDirection.Output;
SqlDataAdapter da = new SqlDataAdapter(cmd);
}
}
}
illustrates how to call a SQL Server stored procedure
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example23_7.cs illustrates how to call a SQL Server
stored procedure
*/
using System;
using System.Data;
using System.Data.SqlClient;
public class Example23_7
{
public static void Main()
{
// formulate a string containing the details of the
// database connection
string connectionString =
"server=localhost;database=Northwind;uid=sa;pwd=sa";
// create a SqlConnection object to connect to the
// database, passing the connection string to the constructor
SqlConnection mySqlConnection =
new SqlConnection(connectionString);
// formulate a string containing the name of the
// stored procedure
string procedureString =
"Ten Most Expensive Products";
// create a SqlCommand object to hold the SQL statement
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
// set the CommandText property of the SqlCommand object to
// procedureString
mySqlCommand.CommandText = procedureString;
// set the CommandType property of the SqlCommand object
// to CommandType.StoredProcedure
mySqlCommand.CommandType = CommandType.StoredProcedure;
// open the database connection using the
// Open() method of the SqlConnection object
mySqlConnection.Open();
// run the stored procedure
mySqlCommand.ExecuteNonQuery();
// create a SqlDataAdapter object
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
// set the SelectCommand property of the SqlAdapter object
// to the SqlCommand object
mySqlDataAdapter.SelectCommand = mySqlCommand;
// create a DataSet object to store the results of
// the stored procedure call
DataSet myDataSet = new DataSet();
// use the Fill() method of the SqlDataAdapter object to
// retrieve the rows from the stored procedure call,
// storing the rows in a DataTable named Products
mySqlDataAdapter.Fill(myDataSet, "Products");
// display the rows in the Products DataTable
Console.WriteLine("The ten most expensive products are:");
DataTable products = myDataSet.Tables["Products"];
foreach (DataRow product in products.Rows)
{
Console.WriteLine("Product name = " +
product["TenMostExpensiveProducts"]);
Console.WriteLine("Unit price = " +
product["UnitPrice"]);
}
// close the database connection using the Close() method
// of the SqlConnection object
mySqlConnection.Close();
}
}
Call Simple Store Procedure
using System;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;
class Class1 {
static void Main(string[] args) {
SqlConnection cnnUserMan;
SqlCommand cmmUser;
object objNumUsers;
// Instantiate and open the connection
cnnUserMan = new SqlConnection("server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI");
cnnUserMan.Open();
// Instantiate and initialize command
cmmUser = new SqlCommand("SimpleStoredProcedure", cnnUserMan);
cmmUser.CommandType = CommandType.StoredProcedure;
objNumUsers = cmmUser.ExecuteScalar();
Console.WriteLine(objNumUsers.ToString());
}
}
Get Return from SQL Server store procedure
using System;
using System.Data;
using System.Data.SqlClient;
class Test
{
public static void Main()
{
SqlConnection mySqlConnection =new SqlConnection("server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
mySqlConnection.Open();
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"EXECUTE @MyProductID = AddProduct3 @MyProductName, " +
"@MySupplierID, @MyCategoryID, @MyQuantityPerUnit, " +
"@MyUnitPrice, @MyUnitsInStock, @MyUnitsOnOrder, " +
"@MyReorderLevel, @MyDiscontinued";
mySqlCommand.Parameters.Add("@MyProductID", SqlDbType.Int);
mySqlCommand.Parameters["@MyProductID"].Direction = ParameterDirection.Output;
mySqlCommand.Parameters.Add("@MyProductName", SqlDbType.NVarChar, 40).Value = "Widget";
mySqlCommand.Parameters.Add("@MySupplierID", SqlDbType.Int).Value = 1;
mySqlCommand.Parameters.Add("@MyCategoryID", SqlDbType.Int).Value = 1;
mySqlCommand.Parameters.Add("@MyQuantityPerUnit", SqlDbType.NVarChar, 20).Value = "1 per box";
mySqlCommand.Parameters.Add("@MyUnitPrice", SqlDbType.Money).Value = 5.99;
mySqlCommand.Parameters.Add("@MyUnitsInStock", SqlDbType.SmallInt).Value = 10;
mySqlCommand.Parameters.Add("@MyUnitsOnOrder", SqlDbType.SmallInt).Value = 5;
mySqlCommand.Parameters.Add("@MyReorderLevel", SqlDbType.SmallInt).Value = 5;
mySqlCommand.Parameters.Add("@MyDiscontinued", SqlDbType.Bit).Value = 1;
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
while (mySqlDataReader.Read())
{
Console.WriteLine("mySqlDataReader[" ProductName"] = " +
mySqlDataReader["ProductName"]);
Console.WriteLine("mySqlDataReader[" UnitPrice"] = " +
mySqlDataReader["UnitPrice"]);
}
mySqlDataReader.Close();
Console.WriteLine("New ProductID = " + mySqlCommand.Parameters["@MyProductID"].Value);
mySqlConnection.Close();
}
}

