/*
* 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 FindingRowsInData
{
public static void Main()
{
SqlConnection MyConnection = new SqlConnection(@"Data Source=(local); Initial Catalog = CaseManager; Integrated Security=true");
SqlDataAdapter MyDataAdapter = new SqlDataAdapter("SELECT * FROM Test", MyConnection);
SqlCommandBuilder MyCmd = new SqlCommandBuilder(MyDataAdapter);
DataSet MyDataSet = new DataSet();
MyDataAdapter.Fill(MyDataSet);
DataColumn[] MyKey = new DataColumn[1];
MyKey[0] = MyDataSet.Tables[0].Columns[0];
MyDataSet.Tables[0].PrimaryKey = MyKey;
DataRow FindMyRow = MyDataSet.Tables[0].Rows.Find(1);
}
}
}
Month: February 2011
illustrates how to perform a SELECT statement using ADO.NET
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example23_1.cs illustrates how to perform a SELECT statement
using ADO.NET
*/
using System;
using System.Data;
using System.Data.SqlClient;
public class Example23_1
{
public static void Main()
{
// step 1: formulate a string containing the details of the
// database connection
string connectionString =
“server=localhost;database=Northwind;uid=sa;pwd=sa”;
// step 2: create a SqlConnection object to connect to the
// database, passing the connection string to the constructor
SqlConnection mySqlConnection =
new SqlConnection(connectionString);
// step 3: formulate a SELECT statement to retrieve the
// CustomerID, CompanyName, ContactName, and Address
// columns for the first ten rows from the Customers table
string selectString =
“SELECT CustomerID, CompanyName, ContactName, Address ” +
“FROM Customers ” +
“WHERE CustomerID < 'BSBEV'";
// step 4: create a SqlCommand object to hold the SELECT statement
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
// step 5: set the CommandText property of the SqlCommand object to
// the SELECT string
mySqlCommand.CommandText = selectString;
// step 6: create a SqlDataAdapter object
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
// step 7: set the SelectCommand property of the SqlAdapter object
// to the SqlCommand object
mySqlDataAdapter.SelectCommand = mySqlCommand;
// step 8: create a DataSet object to store the results of
// the SELECT statement
DataSet myDataSet = new DataSet();
// step 9: open the database connection using the
// Open() method of the SqlConnection object
mySqlConnection.Open();
// step 10: use the Fill() method of the SqlDataAdapter object to
// retrieve the rows from the table, storing the rows locally
// in a DataTable of the DataSet object
Console.WriteLine("Retrieving rows from the Customers table");
string dataTableName = "Customers";
mySqlDataAdapter.Fill(myDataSet, dataTableName);
// step 11: get the DataTable object from the DataSet object
DataTable myDataTable = myDataSet.Tables[dataTableName];
// step 12: display the columns for each row in the DataTable,
// using a DataRow object to access each row in the DataTable
foreach (DataRow myDataRow in myDataTable.Rows)
{
Console.WriteLine("CustomerID = " + myDataRow["CustomerID"]);
Console.WriteLine("CompanyName = " + myDataRow["CompanyName"]);
Console.WriteLine("ContactName = " + myDataRow["ContactName"]);
Console.WriteLine("Address = " + myDataRow["Address"]);
}
// step 13: close the database connection using the Close() method
// of the SqlConnection object created in Step 2
mySqlConnection.Close();
}
}
[/csharp]
Get row count from SqlCommand
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
using System; using System.Data; using System.Data.SqlClient; class CommandExampleNonQuery { static void Main() { SqlConnection thisConnection = new SqlConnection("server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI"); SqlCommand selectCommand = new SqlCommand("SELECT COUNT(*) FROM Employee", thisConnection); SqlCommand nonqueryCommand = thisConnection.CreateCommand(); try { thisConnection.Open(); Console.WriteLine("Before INSERT: Number of Employee is: {0}", selectCommand.ExecuteScalar()); nonqueryCommand.CommandText = "INSERT INTO Employee (Firstname, Lastname) VALUES ('Z', 'Z')"; Console.WriteLine(nonqueryCommand.CommandText); Console.WriteLine("Number of Rows Affected is: {0}",nonqueryCommand.ExecuteNonQuery()); Console.WriteLine("After INSERT: Number of Employee is: {0}", selectCommand.ExecuteScalar()); nonqueryCommand.CommandText = "DELETE FROM Employee WHERE Firstname='Z' AND Lastname='Z'"; Console.WriteLine(nonqueryCommand.CommandText); Console.WriteLine("Number of Rows Affected is: {0}", nonqueryCommand.ExecuteNonQuery()); Console.WriteLine("After DELETE: Number of Employee is: {0}", selectCommand.ExecuteScalar()); } catch (SqlException ex) { Console.WriteLine(ex.ToString()); } finally { thisConnection.Close(); Console.WriteLine("Connection Closed."); } } } |
use ExecuteScalar() to run a SELECT statement that returns a single value
using System;
using System.Data;
using System.Data.SqlClient;
class ExecuteScalar {
public static void Main() {
SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa");
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "SELECT COUNT(*) FROM Products";
mySqlConnection.Open();
int returnValue = (int)mySqlCommand.ExecuteScalar();
Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue);
mySqlConnection.Close();
}
}
Get result data from SqlDataReader by type: decimal, string, int and boolean
using System;
using System.Data;
using System.Data.SqlClient;
class TypedMethods
{
static void Main(string[] args)
{
string connString = "server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";
string sql = @"select * from employee";
SqlConnection conn = new SqlConnection(connString);
try {
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read()) {
Console.WriteLine( "{0} {1} {2} {3}",
// nvarchar
reader.GetString(0).PadRight(30),
// money
reader.GetDecimal(1),
// smallint
reader.GetInt16(2),
// bit
reader.GetBoolean(3));
}
reader.Close();
} catch(Exception e) {
Console.WriteLine("Error Occurred: " + e);
} finally {
conn.Close();
}
}
}
Result set info: field count and field type
using System;
using System.Data;
using System.Data.SqlClient;
class ResultSetInfo{
static void Main(string[] args) {
string connString = "server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";
string sql = @"select FirstName, LastName from Employee";
SqlConnection conn = new SqlConnection(connString);
try {
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine("Column Name: {0} {1}", reader.GetName(0).PadRight(25),reader.GetName(1));
Console.WriteLine("Data Type: {0} {1}", reader.GetDataTypeName(0).PadRight(25), reader.GetDataTypeName(1));
Console.WriteLine("Number of columns in a row: {0}", reader.FieldCount);
Console.WriteLine("'{0}' is at index {1} and its type is: {2}",
reader.GetName(0),reader.GetOrdinal("FirstName"),reader.GetFieldType(0));
Console.WriteLine("'{0}' is at index {1} and its type is: {2}",
reader.GetName(1), reader.GetOrdinal("LastName"),reader.GetFieldType(1));
reader.Close();
}
catch(Exception e)
{
Console.WriteLine("Error Occurred: " + e);
}
finally
{
conn.Close();
}
}
}
Result set info: column Name, column Type, type name
using System;
using System.Data;
using System.Data.SqlClient;
class ResultSetInfo{
static void Main(string[] args) {
string connString = "server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";
string sql = @"select FirstName, LastName from Employee";
SqlConnection conn = new SqlConnection(connString);
try {
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine("Column Name: {0} {1}", reader.GetName(0).PadRight(25),reader.GetName(1));
Console.WriteLine("Data Type: {0} {1}", reader.GetDataTypeName(0).PadRight(25), reader.GetDataTypeName(1));
while(reader.Read()) {
Console.WriteLine(" {0} {1}",
reader.GetString(0).ToString().PadRight(25),
reader.GetString(1));
}
reader.Close();
}
catch(Exception e)
{
Console.WriteLine("Error Occurred: " + e);
}
finally
{
conn.Close();
}
}
}

