ch10_05.cs
来自「《c#技术内幕代码》」· CS 代码 · 共 137 行
CS
137 行
using System;
using System.Data;
using System.Data.ADO;
public class CH10_4
{
public static int GetMenuSelection()
{
Console.WriteLine("Please select how you want to find a record:");
Console.WriteLine("{0} Exit");
Console.WriteLine("(1) By Name");
Console.WriteLine("(2) By City" );
Console.WriteLine("(3) By State");
int selection = -1;
do
{
Console.WriteLine("\nEnter your Selection: ");
string s = Console.ReadLine();
try
{
selection = s.ToInt16();
}
catch
{
selection = -1;
}
} while ( selection < 0 || selection > 3 );
return selection;
}
public static void Main ()
{
// Define the connection string
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=CH10.MDB";
// Find out what they want to delete.
Boolean done = false;
while ( !done )
{
string value = "";
string strSelect = "";
switch ( GetMenuSelection() )
{
case 0:
done = true;
break;
case 1: // Name
Console.WriteLine("Enter name to find: ");
value = Console.ReadLine();
strSelect = "SELECT * from Contact where Name Like \"";
break;
case 2: // City
Console.WriteLine("Enter city to find: ");
value = Console.ReadLine();
strSelect = "SELECT * from Contact where City Like \"";
break;
case 3: // State
Console.WriteLine("Enter state to find: ");
value = Console.ReadLine();
strSelect = "SELECT * from Contact where State Like \"";
break;
}
if ( done )
break;
strSelect += value;
strSelect += "\";";
// Create the connection object, using our connection string
ADOConnection myConn = new ADOConnection(strConn);
// Create the command object from our selection criteria string
ADOCommand myCmd = new ADOCommand( strSelect, myConn );
// Try to execute the command
ADODataReader outData = null;
try
{
// This will do the connection to the database
myConn.Open();
// This will run our query and put the result in outData
myCmd.Execute( out outData );
// See if we got something back
if ( outData != null )
{
while (outData.Read() )
{
Console.WriteLine( "ID: {0}", outData["ID"]);
Console.WriteLine( "Name: {0}", outData["Name"]);
Console.WriteLine( "Address: {0}", outData["Address"]);
Console.WriteLine( "City: {0}", outData["City"]);
Console.WriteLine( "State: {0}", outData["State"]);
Console.WriteLine( "Zip Code: {0}", outData["ZipCode"]);
Console.WriteLine( "Age: {0}", outData["Age"]);
Console.Write("\nDo you wish to delete this record (y/n):");
string resp = Console.ReadLine();
if ( resp == "y" || resp == "Y" )
{
int id = (int)outData["ID"];
outData.Close();
strSelect = "DELETE from Contact where ID = ";
strSelect += id;
strSelect += ";";
ADOCommand cmd = new ADOCommand( strSelect, myConn );
try
{
outData = null;
cmd.Execute( out outData );
}
catch ( Exception e )
{
Console.WriteLine("Exception in delete {0}", e );
}
break;
}
}
}
}
catch ( Exception e )
{
Console.WriteLine("Exception {0}", e );
}
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?