Advertisement
3_2004-2005 Math #146139

Various math operations

Factorial, list prime numbers to a given amount, factor a positive integer, matrix multiplication (the fun part), and test to see if the inputed value was a number and not letters or excess decimal points/neg. signs.

AI

Shrnutí AI: This codebase represents a historical implementation of the logic described in the metadata. Our preservation engine analyzes the structure to provide context for modern developers.

Zdrojový kód
original-source
// James Sibley
// 17-19 October 2001
// Period 6
// Made up problem.... solved :P
#include <iostream>
#include <fstream>
#include <windows.h>
#include <math.h>
#include <cstdlib>
#include <iomanip>
using namespace std;
/* Functions that will be used */
void listprimes(); // Make a list of prime numbers
void factor(); // Factor a number or let you know that it is prime
void quadratic(); // Use the quadratic equation
void matrix();   // Matrix multiplication
void factorial(); // Find the factorial of a number
bool notvalid(char[]); // Did the user input a correct number?
/* Stucture used to hold the name and address of the functions */
struct m
{
	char name[256]; // Char to hold the name that will appear on the menu
	void (*list)(); // Pointer to a function
} menu[] = {    // Creating an array of data type "m"
	"Factorial", factorial, // Name to appear on menu and address of function
	"List Prime numbers", listprimes,
	"Factor a number", factor,
	"Quadratic formula", quadratic,
	"Matrix multiplication", matrix
};
void main(){ // Void main - do not return a value
	
	int size = sizeof(menu)/sizeof(m); // Find the # of items to include on menu
	int x; // loop variable
	char input[64] = "-1"; // Input variable for the menu
	bool exit = false; // Looping condition
	while(!exit) {
		
		// If the user entered anything other than the list provides or
		// The number was less than 0, keep looping
		while(atoi(input) > size || atoi(input) < 0) {
			system("cls"); // Clear the screen
			cout << "Select a number from the list\n";
			for(x = 0; x < 80; x++) // Output 80 *s which will cover the
				cout << "*";    // width of the screen
			// Output the menu
			// menu[x].name means that we are selecting an item from an
			// array of a structure. This array holds key information.
			// This information is the name to include in the outputed
			// menu and the address of the function to call if that item
			// is selected... :)
			for(x = 0; x < size; x++)
			{
				cout << x+1 << ": " << menu[x].name << "\n";
			}
			
			cout << "0: Exit\n";
			for(x = 0; x < 80; x++) // Output more *s...
				cout << "*";
	
			cout << "[?]: "; // This is the prompt the user will see
			cin.getline(input,64);	 // The user will input a selection from the menu
			if(notvalid(input) || input[0] == '\0') {
				strcpy(input, "-1");
				continue;
			}
		}
	
		if(strcmp(input,"0") == 0) {
				exit = true;
				break;
		// If the user picked something on the list other than zero,
		// the choice will be evaluated here. Here, we will call
		// a function through its address found in the array we created
		// for the menu
		}else{
				cout << "\n";
				(*menu[atoi(input) - 1].list)();
		}
		system("pause");
		strcpy(input, "-1");
	}
}
/* This function will list prime numbers to a user-inputed amount */
void listprimes() {
	int x, y; char SIZE[64] = {1}; // loop variables... except SIZE..
					// SIZE will be the size of a bool array
	bool *prime;  // pointer to a future list of prime numbers
	char save[512]; // Where the user feels like saving the file...
	while(notvalid(SIZE) || atoi(SIZE) < 2) {
		cout << "Enter a valid number: ";
		cin.getline(SIZE,64);  // prime numbers 1 to SIZE
	}
	cout << "Enter the path/file to save the file: ";
	cin >> save;  // Save the file... HERE!
	prime = new bool[atoi(SIZE)]; // Create a bool array based on SIZE
							// If you imput a number in this array
							// later on, it will return whether or
							// not it is prime... neato!
	// We are going to assume for the moment that all the numbers
	// are prime... only because i said so...
	for(x = 1; x <= atoi(SIZE); x++)
		prime[x-1] = true;
	prime[0] = false; // 1 is not a prime number
	/* calculate prime numbers */
	
	// This is the neat part. Here we are going to determine
	// all the numbers that are not prime. This is done by dividing
	// all numbers by 2 to the square root of (SIZE). If a number is
	// found to be divisible, then the number is said to not be prime
	// and prime[x-1] = false. All numbers left being "true" are prime
	// numbers.
	
	for(x = 4; x <= atoi(SIZE); x++){
		for(y = 2; y < (sqrt(x)+1); y++)
			if(x%y == 0){
				prime[x-1] = false;
				break;} // break out of the loop if a composite number
	}					// is found... !!!!! This saves time by not
						// having to loop through meaningless numbers
	/* end calulation */
	ofstream primefile(save, ios::trunc); // creating a file to save
										 // the list
	primefile << "Prime numbers: 1 - " << atoi(SIZE) << "\n"; // outputting
												    // to the file
	// This will output to the file ONLY the prime numbers by looking
	// for those in the bool array that remain true... sweet!
	cout << "\n";
	for(x = 1; x <= atoi(SIZE); x++)
		if(prime[x-1] == true)
			primefile << x << "\n";
	// For fun... a message box in Windows (WinBlowz, hehehe)...
	MessageBox(NULL, "Complete! List of prime numbers has been created.\n\n:)",
		    "Done", MB_OK | 48);
	delete [] prime;
}
/* this function will factor a number. If it is prime, it will inform you. */
void factor(void) {
	char number[64] = {0}; // The number that they enter
	long remainder; // remainder after we divide a divisible number
	long *factors; // all the factors of a number go here
	long counter = 0; // the number of factors in a number
	long x; // looping variable
	for(;;) { // infinite loop
		strcpy(number,"8388609");
		while(atoi(number) > 8388607 || atoi(number) < 2 || notvalid(number))
		{
			cout << "[Enter number to test factor, 0 to stop, up to 8388607]: ";
			cin.getline(number,64);
			if(atoi(number) == 0)
				return;
		}
		
		// Make an array half the size a the inputed number.
		// This is because if all the factors are 2, then the
		// number of factors will be half of that number
		factors = new long[atoi(number) / 2];
		remainder = atoi(number);
		

		long half = atoi(number) / 2 + 1;
		long temp; // the remainder of the remainder divided by
				  // a tested number
		counter = 0;
		/* find factors */
		// all this peice of code does is divide it
		// by 2 to half the number... if it is divisible
		// by x... then that is a factor and x is set back
		// to 2. Factors[counter] will hold the factors
		for(x = 2; x <= atoi(number); x++) {
			temp = remainder%x;
			if(temp == 0) {
				factors[counter] = x;
				counter++;
				remainder /= x;
				x = 1;
			}
		}
		/* End find factors */
		factors[counter] = 0;
		// If the counter went through one time, then
		// the number is prime. If the number is not prime,
		// it will display every prime factor of the
		// inputed number
		if(counter == 1) {
				cout << "Prime number";
				factors[0] = 0;
		}else {
			x = 0;
			while(factors[x]){
				cout << factors[x] << " ";
				x++; }
			}
			cout << "\n";
		}
	delete [] factors; // Delete the array
}
/* This function will find the x intercepts and */
/* tell what the vertext is           */
void quadratic() {
	char a[64] = {1}, b[64] = {1}, c[64] = {1}; // numbers used in ax^2 + bx + c
	bool inter; // true if y can equal zero
	double first, second; // the first and second intercepts
	char pre[64] = {1}; // the decimal precision
	cout << "For ax^2 + bx + c, enter in the following pieces of information\n";
	while(notvalid(a)) {
		cout << "a = ";
		cin.getline(a,64);
	}
	// "a" cannot be zero because if it was, it would not be a parabola
	// and you would be dividing by zero. anything divided by zero is
	// so huge that it is undefined...
	while(atoi(a) == 0 || notvalid(a)) {
			if(atof(a) == 0) cout << "\'a\' may not equal 0!\n";
			cout << "a = ";
			cin.getline(a,64);
	}
	while(notvalid(b)) {
		cout << "b = ";
		cin.getline(b,64);
	}
	while(notvalid(c)) {
		cout << "c = ";
		cin.getline(c,64);
	}
	while(notvalid(pre)) {
		cout << "Enter the decimal precision: ";
		cin.getline(pre,64);
	}
	cout << "\n";
	for(int x = 0; x < 80; x++)
		cout << "*";
	// Find the value of the disciminant (spelling?).
	// I am not sure if the "Unknown error!" part will ever execute,
	// but it could be possible... so i just included it to prevent
	// a program crash during unknown errors (which does happen)
	double dis = atof(b) * atof(b) - 4 * atof(a) * atof(c);
	if(dis < 0){
		cout << "X-intercepts lie on the imaginary-axis!\n";
		inter = false;
	}else if(dis == 0) {
		cout << "Vertex lies on x-axis!\n";
		inter = true;
	}else if(dis > 0) {
		cout << "Two points cross the x-axis!\n";
		inter = true;
	}else {
		cout << "Unknown Error!\n";
		inter = false;
	}
	// If the parabola does cross the x-axis atleast once,
	// then the answers are evaluated here...
	if(inter) {
		cout << "X-intercepts: (";
		first = (-1 * atof(b) + sqrt(dis))/(2 * atof(a));
		cout << setprecision(atoi(pre)) << first << ",0) - (";
		second = (-1 * atof(b) - sqrt(dis))/(2 * atof(a));
		cout << setprecision(atoi(pre)) << second << ",0)\n";
	}
	
	// The vertex of a parabola is equal to (-b)/(2a)
	// for the x value. To find the y value, just plug
	// x in
	double vertex = (-1 * atof(b)) / (2 * atof(a));
	cout << "Vertex: (" << setprecision(atoi(pre)) << vertex
		 << "," << setprecision(atoi(pre)) << atof(a)*vertex*vertex + atof(b) * vertex + atof(c) << ")\n";
	for(x = 0; x < 80; x++)
		cout << "*";
}
/* This function will multiply to matrices together. */
void matrix()
{
	// These are the dimensions of the two
	// matrices...
	char dim1[64] = "0", dim2[64] = "0", dima1[64] = "0", dima2[64] = "0";
	
	// prompting the user to enter enter valid dimensions
	while(atoi(dim1) == 0 || atoi(dim2) == 0 || notvalid(dim1) || notvalid(dim2))
	{
		cout << "Enter the first dimension for matrix one: ";
		cin.getline(dim1,64);
		cout << "Enter the second dimension for matrix one: ";
		cin.getline(dim2,64);
	}
	
	// Not only does the user have to enter valid dimension
	// for the second matrix... but the first one has
	// to be the same as the last one of the first matrix...
	// if not, multiplication will not be possible
	while(atoi(dima1) == 0 || atoi(dima2) == 0 || atoi(dima1) != atoi(dim2) || notvalid(dima1) || notvalid(dima2))
	{
		cout << "Enter the first dimension for matrix two: ";
		cin.getline(dima1,64);
		cout << "Enter the second dimension for matrix two: ";
		cin.getline(dima2,64);
	}
	// Initalizing three, 2500-entry each matrices...
	double matrix1[50][50] = {{0},{0}};
	double matrix2[50][50] = {{0},{0}};
	double pmatrix[50][50] = {{0},{0}};
	char temp[64] = {1};
	// Ask the user to enter in the values for the first matrix
	// and then storing the values.
	for(int x = 0; x < atoi(dim1); x++) {
		for(int y = 0; y < atoi(dim2); y++)
		{
				cout << "Enter \'" << x+1 << y+1 << "\' for matrix one: ";
				cin.getline(temp,64);
				if(notvalid(temp)) {
					y--;
					continue;
				}else{
					matrix1[x][y] = atof(temp);
					strcpy(temp, "\x01");
				}
		}
	}
	
	// Ask the user to enter in the values for the second matrix
	// and then storing the values.
	for(x = 0; x < atoi(dima1); x++) {
		for(int y = 0; y < atoi(dima2); y++)
		{
			cout << "Enter \'" << x+1 << y+1 << "\' for matrix two: ";
			cin.getline(temp,64);
			if(notvalid(temp)) {
				y--;
				continue;
			}else{
				matrix2[x][y] = atof(temp);
				strcpy(temp, "\x01");
			}
		}
	}
	// This is where the matrices are multiplied together.
	for(x = 0; x < atoi(dim1); x++) {
		for(int y = 0; y < atoi(dima2); y++) {
			for(int z = 0; z < atoi(dim2); z++) {
					pmatrix[x][y] += matrix1[x][z]*matrix2[z][y];
			}
		}
	}
	
	// This code will display the results of the multiplication
	for(x = 0; x < atoi(dim1); x++) {
		cout << "\n[";
		for(int y = 0; y < atoi(dima2); y++) {
			cout << pmatrix[x][y];
			if((y + 1) != atoi(dima2))
				cout << " ";
		}
		cout << "]";
	}
	cout << "\n";
}
/* This function will find the factorial of a number */
void factorial()
{
	char number[64] = {1}; // the number the user inputs
	double long hold;
	while(atol(number) < 0 || notvalid(number)) {
		cout << "Enter a number for the factorial operation: ";
		cin.getline(number,64);
		// Check to see if the user selected a number that is
		// not zero or negative
		if(atol(number) < 0 || notvalid(number)) {
			cout << "Not Valid!\n";
		}
	}
	if(atol(number) == 0 || atol(number) == 1) {
		cout << "\n" << atol(number) << "! = 1\n";
		return;
	}
	hold = (long)atof(number);
	double long total = 1;
	// factorial a number
	// (can factorial be used as a verb? :P )
	for(double long x = hold; x >= 1; x--) {
		total *= x;
	}
	cout << "\n" << setprecision(20) << atol(number) << "! = " << total << "\n";
}
/* this is determine if a string contains valid numbers and parts */
bool notvalid(char input[])
{
	int x = 0, decCounter = 0, negCount = 0, cond;
	if(strcmp(input, "-") == 0 || strcmp(input, ".") == 0)
		return true;
	while(input[x]) {
		cond = (input[x] >= '0' && input[x] <= '9') || input[x] == '.' || input[x] == '-';
		if(!cond)
			return true;
		x++;
	}
	x = 0;
	while(input[x]) {
		if(input[x] == '.')
			decCounter++;
		else if(input[x] == '-')
			negCount++;
		if(decCounter > 1 || negCount > 1)
			return true;
		x++;
	}
	x = 1;
	while(input[x]) {
		if(input[x] == '-')
			return true;
		x++;
	}
	return false;
}
<h1><span style='font-size:12.0pt'>ADO.Net Primer + Programming databases using
OLE DB with ADO.Net<o:p></o:p></span></h1>
<p class=MsoNormal><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt;
font-family:Verdana'>By Cyril Gupta<o:p></o:p></span></p>
<p class=MsoNormal><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt;
font-family:Verdana'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></span></p>
<p class=MsoBodyText>Although I’ve been working with Visual Basic for several
years now (started with Visual Basic 3.0), and I was quick to adopt the newer
versions of Visual Basic as they came, I was a rather late entrant on the .Net
scene. </p>
<p class=MsoNormal><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt;
font-family:Verdana'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></span></p>
<p class=MsoNormal><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt;
font-family:Verdana'>But migration to .Net had to occur eventually, so here I
am working with .Net, and to keep me company, I’ve decided to write a series of
articles.<o:p></o:p></span></p>
<p class=MsoNormal><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt;
font-family:Verdana'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></span></p>
<h2>Acessing Local Databases</h2>
<p class=MsoNormal><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt;
font-family:Verdana'>Read .Net books or tutorials and they will tell you that
data access in VB.Net is pretty straightforward using Ado.Net, Microsoft’s
replacement for ADO. However, if you’ve been using DAO and ADO long enough like
I, you’ll soon be lost among the swamp of new classes and properties that ADO.Net
exposes. <o:p></o:p></span></p>
<p class=MsoNormal><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt;
font-family:Verdana'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></span></p>
<p class=MsoBodyText>ADO.Net has two primary clients to establish the
connection with the data: The SQLClient and OLEDB.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>The SQLClient is designed to connect only and only to
Microsoft SQL Server databases, while the OLEDB client allows you to connect to
any database that has an OLE DB server. </p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>This is where I was lost for quite a while. Almost all of
the examples in database programming books that I saw were exclusively based on
the SQLClient class. Good, but what about the programmers who don’t use SQL
Server, or make applications that has to be deployed on PCs that don’t have SQL
Server installed?</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>As a maker of packaged applications I use Jet Databases
most of the time and my apps are used by thousands of users. I can’t force them
to install SQL Server.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>You’ve got two options.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText><b>a) Stick to ADO<o:p></o:p></b></p>
<p class=MsoBodyText>The .Net framework has full support for Microsoft ADO
database access. You can declare ADO classes, and use them the same way you’d
use them in your Visual Basic 6 project. </p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>To use ADO add a reference to the ‘adodb’ .Net component
by right clicking on ‘References’ in your project, and then selecting ‘adodb’
from the Components list. This will allow you to create instances of all the
ADODB classes like Connection, Command and Recordset, and you will never notice
that you’re working with .Net. </p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>I am not going to show you the code to do this as you
probably already know how, and if you don’t, you can look at the million or so
code examples on the Internet. </p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>That was the easy way out, and that is what I decided to
do at first. However, when I began, something didn’t feel right. True cowboys
don’t take the easy way out, and I am not inferior in courage, or guts to any plain old cowherd.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Also there’s one more disadvantage. Microsoft.Net does not
use really compiled applications, actually the applications that we make are
compiled to MSIL (Microsoft Intermediate Language) and a Just-In-Time compiler
is used to compile then when they’re run. ADO isn’t natively supported in .Net
so it can’t be compiled to MSIL. Your code will still compile and work, but it
will use COM Interoperability, so the disadvantage is purely from a technical
point of view.<span style='text-transform:uppercase'><o:p></o:p></span></p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Let’s explore the second option.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText><b>b) Use OLEDB<o:p></o:p></b></p>
<p class=MsoBodyText>Just about when I was about to give up on SQLClient and go
back to ADO to access my local databases, I found somewhere that OLEDB is the
interface to use to access all kinds databases with ADO.Net. This naturally
includes Jet databases.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>This is what I decided to use, and this is what the rest
of this tutorial talks about.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText><b><span style='font-size:12.0pt'>Programming OLEDB <o:p></o:p></span></b></p>
<p class=MsoBodyText>The OLEDB does not provide the same kind of ease of use or
features like ADO or SQLClient does. The class is stricter, and unlike ADO
objects that allow you to declare and initialize the objects in a wide variety
of ways through polymorphed functions, OLEDB objects are harsher and less
adaptable. </p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Properties like Connection.Provider that you could assign
data to in ADO, are read only in OLEDB, which caused me a lot consternation
when I began using the objects.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Primary OLEDB Objects that you will need to access data:</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText style='margin-left:1.0in;text-indent:-.25in;mso-list:l1 level1 lfo2;
tab-stops:list 1.0in'><![if !supportLists]><span style='font-family:Symbol'>·<span
style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span></span><![endif]>OLEDBConnection</p>
<p class=MsoBodyText style='margin-left:1.0in;text-indent:-.25in;mso-list:l1 level1 lfo2;
tab-stops:list 1.0in'><![if !supportLists]><span style='font-family:Symbol'>·<span
style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span></span><![endif]>OLEDBCommand</p>
<p class=MsoBodyText style='margin-left:1.0in;text-indent:-.25in;mso-list:l1 level1 lfo2;
tab-stops:list 1.0in'><![if !supportLists]><span style='font-family:Symbol'>·<span
style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span></span><![endif]>OLEDBDataAdapter</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText><b>OLEDBConnection<o:p></o:p></b></p>
<p class=MsoBodyText>You can call this a replacement for the ADODB.Connection
object. It behaves in a similar manner, and you can open the database the same
way you did with the ADODB.Connectionstring. However, unlike ADODB.Connection
object, most methods in OLEDBConnection object do not support polymorphic
arguments the same way that ADODB.Connection does. </p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>How does this affect you? For example, you won’t be able
to assign values to OLEDBConnection.Provider or OLEDBConnection.Datasource like
you did with ADODB. All these properties are read only in OLEDB and you will
have to specify everything in the ConnectionString property.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Here’s some sample code.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoNormal style='mso-layout-grid-align:none; text-autospace:none; color: #000099;'><span
style='font-size:10.0pt;font-family:"Courier New"'>cnn.ConnectionString =
&quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\dic.mdb;&quot;<o:p></o:p></span></p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>This connectionstring opens a Microsoft Jet 4 Database
named ‘dic.mdb’ located in ‘c:\’.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Here-</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Provider = The database service provider name. If you use
Jet Databases (.MDB) this will mostly be ‘Microsoft.Jet.OLEDB.4.0’ for the new
Acess 2000 databases, and ‘Microsoft.Jet.OLEDB.3.5’ for older databases. You
can open Jet 3.5 databases with Jet 4.0 but not vice-versa. So if you create a
database using the new version of Microsoft Access and not the Database wizard
in Visual Basic 6 then you will have to use the 4.0 provider.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Data Source = The database name. This can be a file, or a
database name if you use a database server like MS Sql Server. Yes, you can
open SQL Server databases using OLEDB object instead of SQLClient if you want
to. </p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Don’t forget to put the semicolon ‘;’ mark after each
attribute, or the code won’t work.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText><b><span style='font-size:12.0pt'>OLEDBCommand<o:p></o:p></span></b></p>
<p class=MsoBodyText>The OLE DB command object allows you to execute SQL
procedures on your data tables and to retrieve data from the table.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>To get the records from our data table we must first
assign the connection object to the connection property of the command object.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText style1>myCommand = myConnection;</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Now set the ‘Commandtype’ property. The CommandType
property tells OLEDB what kind of command you wish to execute.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>You have three options.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText><b>CommandType<o:p></o:p></b></p>
<p class=MsoBodyText>Text – A normal SQL Query.</p>
<p class=MsoBodyText>StoredProcedure – The procedure name of a stored procedure
in the database.</p>
<p class=MsoBodyText>TableDirect – The Tablename of the table to open.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Most of the time you’ll find yourself using the Text
property or the TableDirect property. However it’s a great idea to use Stored
Procedures in a database to do frequently performed operations.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>I going to set my CommandType to Text for the moment.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText style2>myCommand.CommandType = CommandType.Text</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Now you must tell the Command object what Query string to
use.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText style1>myCommand.Text = “SELECT * FROM DIC WHERE WORD LIKE ‘A%’”</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>This will retrieve all rows of the DIC table in which the
Word column starts with the letter ‘A’.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>If you used the TableDirect CommandType then you can
simply assign the name of the table to the Command.Text property. This would
look like this.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText style1>myCommand.Text = “Dic”</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>This will retrieve all the rows in table Dic.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText><b>More about Queries<o:p></o:p></b></p>
<p class=MsoBodyText>Before we move on to learning how to use the data retrieved
from the query let’s learn a little about Executing queries using the Command
object.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>The Ole DB Command object supports three kinds of Execute
statements.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>ExecuteNonQuery – Execute an SQL statement that does not
return a result.</p>
<p class=MsoBodyText>ExecuteReader – Execute an SQL statement that returns a
DataReader object (More about it later.)</p>
<p class=MsoBodyText>ExecuteScalar – Execute an SQL statement that returns the
first column of the resultant recordset.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>In ADO you could also execute an SQL statement to return a
recordset object that was updateable and editable, this is no longer supported
with ADO.NET. Now you must use Datasets, which can be compared more favorably
with disconnected recordsets even though the comparison is not very apt. More
about DataSets later, let’s see a sample of each type of query statement first.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Examples Query Statements</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText style1>myCommand.Text = “DELETE * From Dic”</p>
<p class=MsoBodyText style1>myCommand.ExecuteNonQuery</p>
<p class=MsoBodyText style3>Will delete everything from the table Dic.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText style1>myCommand.Text = “SELECT * From Dic”</p>
<p class=MsoBodyText style1>myDataReader = myCommand.ExecuteReader</p>
<p class=MsoBodyText style4>Will get everything from the table Dic and you can assign
to a DataReader object.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText style1>myCommand.Text = “SELECT * From Dic”</p>
<p class=MsoBodyText style1>myVar = myCommand.ExecuteScalar</p>
<p class=MsoBodyText style3>Will the first column of the first record from the table
Dic. You can assign this value to a variable.</p>
<p class=MsoBodyText><span class="style3">
 <![if !supportEmptyParas]>
 &nbsp;
 <![endif]>
 <o:p></o:p></span><o:p></o:p></p>
<p class=MsoBodyText>Now let’s come to the most important changes in ADO.NET</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText><b><span style='font-size:12.0pt'>DataReader, DataAdapters
&amp; DataSet<o:p></o:p></span></b></p>
<p class=MsoBodyText>With the DataReader object you can get a forward only,
read only set of records from the database. The DataReader object establishes a
really fast connection to the record data and you should use it whenever
possible. </p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText><b>Using DataReaders<o:p></o:p></b></p>
<p class=MsoBodyText>Once you’ve populated a DataReader object with records you
can use the DataReader.Read property to read the column values from the
recordset. On calling Read the DataReader object will automatically move to the
next record.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText><b>DataAdapters<o:p></o:p></b></p>
<p class=MsoBodyText>DataAdapters work as a link between data sources and
DataSets. To get records from or update records to any data source you must go
through a DataAdapter in ADO.Net. </p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>First tell DataAdapter what Command to use using the
‘SelectCommand’ property.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText style2>myDataAdapter.SelectCommand = myCommand</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Now you can fill a DataSet with the resulting records.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText style2>MyDataAdapter.Fill(myDataSet,”myTable”)</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText><b>DataSets<o:p></o:p></b></p>
<p class=MsoBodyText>The closest comparison of an ADO.Net DataSet would be a
disconnected Recordset in ADO. The DataSet also has XML capabilities and can
read or write XML files direct.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>You can browse the data inside a DataSet using the Tables
collection in the DataSet once you’ve filled it using the DataAdapter’s fill
method.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>To iterate through all the rows in a DataSet you can use
the Rows collection of the table.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>
 <span class="style5">&nbsp;
 <![endif]>
 <o:p></o:p></span></p>
<p class=MsoBodyText style2>Dim myDatRow as Data.DataRow ‘Declare a Datarow</p>
<p class=MsoBodyText style2><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText style2>For Each rsRow in MyDataSet.Tables(“myTable”).Rows</p>
<p class=MsoBodyText style2><span style='mso-tab-count:1'>          </span>Console.WriteLine(“MyColumn”)</p>
<p class=MsoBodyText style2>Next</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>This will iterate through the entire table and write the
value of the column “MyColumn” to the Console window.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText><b>Updating Databases<o:p></o:p></b></p>
<p class=MsoBodyText>You cannot directly update using the DataSet object like
you could with a RecordSet in ADO. To update records to a database you must go
through a DataAdapter Object.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>To add new records or rows to the Dataset you can call the
Add method of the Rows collection of the Table. The Add method either accepts a
new Row object as a parameter or an array filled with values for the new row.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Example:</p>
<p class=MsoBodyText style1>MyDataSet.Tables(“MyTable”).Rows.Add(myNewRow)</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>You can change the values in the row by simply selecting
the required Row and then assigning new values to the columns (No need to call
any ‘Edit’ method)</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Once you’ve finished making changes to the DataSet you can
commit the changes to the Database by calling the DataAdapter’s Update method
and passing the changed DataSet as the parameter.</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Example.</p>
<p class=MsoBodyText style1>myDataAdapter.Update(myDataSet)</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>This winds up the ADO.Net Primer for about now. ADO.Net is
big and this primer is by no means complete. I intend to write more episodes of
the primer and introduce the other features of ADO.Net. The next primer in this
series would most probably be based on processing XML through ADO.Net.</p>
<p class=MsoBodyText><br>
Adios until then</p>
<p class=MsoBodyText><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
<p class=MsoBodyText>Cyril Gupta</p>
Původní komentáře (3)
Obnoveno z Wayback Machine