Fundamentals of C # Language and database Technology review

Source: Internet
Author: User
Tags aliases constant definition mathematical functions modifier readline string format

Organized the base of the C # language and database technology, as a review material

Chapter I.

One, C # and Java comparison: 1.c# with Namespaces (namespace) Java Packages (package)

2. Introduce the keyword for namespaces or Packages C # with Using,java import

3. Program entry: C # main () has four forms of static void Main (string[] args)

static int Main (string[] args)

static void Main ()

static int Main ()

Java's main () has a form

4. Variable naming rules: C # begins with a letter and an underscore, and Java begins with a letter underscore and a $

5. Data type comparison: Int,float,double, the two are the same,

String Java using string

C # with String. Boolean Java with bool C #

5. Line comments and block comments are the same//and/*...*/document comments, C # with//, each line starts with//

Second, constant definition: const data type constant name = value;

Third, use placeholder output information: Console. WriteLine ("{0}{1}", Name,age);

Four, console. ReadLine (); Returns the string type, converted with the parse int age=int.parse (console. ReadLine ());

Method named by the Pascal method, each word starts with uppercase; variable name hump method, first letter lowercase, after the first letter of the word capital;

Six, debug Program: F5: Start Debugging

SHIFT+F5: Stop Debugging

F9: setting or canceling breakpoints

CTRL+F9: Cancel Breakpoint

F10: Single Step execution

F2: Go to the definition of the called procedure or variable

CTRL+F2: Shift focus to drop-down list box for class

Chapter II C # syntax quick warm up

One, Java and C # choice structure comparison: 1. Brace notation Specification c#if and else occupy a row such as: if

{


}

JAVA left Curly brace immediately after if or else, the closing parenthesis is another line

In the 2.switch selection structure, C # requires that each case and default have a break statement, unless between 2 case

There are no other statements, and a result is executed at the same time.

Java does not insist, there is no break continue to execute the downstream.


In the 3.switch selection structure, the switch parentheses in C # can use the string variable int, char

Java cannot use string, only int or char

Second, the array of Java and C # Comparison: 1. declaration in different ways Java declares an array in 2 ways: Data type [] array name;

Data type array name [];

C # has only one: data type [] array name;

2. Initialization: When Java Initializes an array, assign values directly to the array, such as: int names[]=new int[]{1,2,3};

Int[] Names=new int[]{1,2,3};

int[] Names=new int [3];

Names[0]=1;

names[1]=2;

...

Int[] names={1,2,3};

But can not use int[] names=new int[3]{1,2,3};

That is, you cannot assign a value to the length of an array

C # When assigning values to an array: int[] names=new int[3]{1,2,3};

can also int [] names=new int[]{1,2,3};

can also int[] names={1,2,3};

To assign values to an object array element, instantiate the object first, and then assign a value to the field for each object, such as:

Defining an array of objects

Student[] Stu=new student[3];

Assigning values to an object array element

Stu[0]=new Student ();

Stu[0].name= "";

Stu[0].age= "";

Loop structure: C # and Java have a while loop, Do-while Loop, for loop, syntax structure, but C # has a more cyclic foreach structure

Syntax: foreach (element type element variable name in array) such as://The number in an array of output arrays

Int[] Array=new int[5]{0,1,2,3,4};

foreach (int item in array)

{

Console. WriteLine (item+ "");

}

The foreach struct cannot change the values of the elements in the array, but only performs the specified action on each data to traverse all the values of the given array.

such as each word in the output string:

String str= "Fly, bird";

Looping output characters

foreach (char c in str)

{

Console.WriteLine (c);

}

In addition to using break in switch, can also be used in the loop structure, so that the program jumps out of the current loop structure, continue to execute the statement after the loop

Continue is similar to break and appears in the loop structure. The function is to exit this loop of the current loop structure and start executing the current loop

The next loop does not exit the current loop structure.

Six, bubble sort: (Ascending formula)

n numbers to queue, 22 compared to small front, outer loop N-1, inner loop n-1-i;

If you want to sort in descending order, simply change the greater-than sign in the program to less than the number.

such as://bubble Sort output Score

Int[] Scores=new int[5];

for (int i=0;i<scores. length-1;i++)

{

for (int j=0;j<scores. length-1-i;j++)

{

if (scores[j]>scores[j+1])

{

int TEMP=SCORES[J];

SCORES[J]=SCORES[J+1];

Scores[j+1]=temp;

}

}

}

Post-order output

Console.WriteLine ("Post-sorting result");

for (int i=0;i<scores. length;i++)

{

Console.WriteLine ("{0}", Scores[i]);

}


Chapter III using attribute upgrade MYbank

The default access modifier for a member in C # is private, and the default for the class is internal.

The This keyword refers to the current object itself, which resolves the problem of member variables and local variable name collisions.

This represents the object reference of the calling method, which is the object to which this method is called. This is non-static and cannot be used in static methods

Class Student

{

private string _name;

public void SetName (string _name)

{

This._name=_name;

}

}

Third, encapsulate fields with attributes

Pivate string _name;

public string Name

{

Get{return _name;}

Set{_name=value;

}

}

Property access type: 1. Read-only property that contains only the get accessor

2. Write-only property that contains only the set accessor

3. Read and write properties, including get and set accessors

Encapsulate Field shortcut key: Ctrl+r,e

C # uses different methods for naming private fields and properties of a class: 1. When naming a private field for a class, start with the underscore "_" and name it with the Hump method

2. Name the attributes of the class using Pascal, capitalized in the first letter

Iv. the difference between fields and attributes: You typically designate a field as private, use it inside a class, designate a property as public, expose it externally,

Provides secure, valid range protection for a field through a get or set accessor.

The difference between attributes and methods: The property set accessor and the get accessor are not used (), because the accessor does not return a value, so it is not necessary to specify void.

Vi. reference passing and value passing differences: A value pass is a copy of the value of a variable that is passed to the method so that the parameter of the method is the same as the value of the argument. In the called

Modifying a parameter in a method only updates the data of the actual parameter replica, and does not actually change the value of the argument.

A reference pass is a reference to the object being passed to the method's formal parameter so that the called method directly references the object

Make changes that affect the original value of the argument. The ref modifier parameters are used both in the method definition and in the method invocation, and

Parameters that are decorated with ref must be assigned a value in the method that is called.


Chapter III in-depth C # string class

One, commonly used string processing method P99

Two, format formatted string name= "Zhang San";

int age=23;

String str= "name {0} age {1}";

Str=string. Format (Str,name,age);

Console.WriteLine (str);

Iii. conversion of numeric types to strings

1,. Convert a string to a numeric type

Int.parse (string str);

Double.Parse (string str);

Float.parse (string str);

2.//numeric conversions to strings with the ToString () method

String Str=num. ToString ();

3. Using the Convert conversion

Convert Convert.ToInt32 () to shaping int

Convert.tosingle () converted to single-precision float

Convert.todouble () converts to double-precision doubles

Convert.ToString () converted to string type strings

When you convert to int with convert, it is rounded, and the value after the decimal point is discarded with parse directly.

Iv. use of the conversion

1. Implicit conversions: Often used between numeric types, converting a numeric type with a small value range to a numeric type with a large range of values

2. Display conversions: Commonly used between numeric types, convert a numeric type with a large range to a numeric type with a range of values that are small

3.Parse () Method: Convert a string to another type

4.Convert class: Conversion of any basic type to another


Eighth. Manipulating data with SQL statements

First, SQL full name is "Structured Query Language" (Structured queries Language)

Ii. operators in sql: 1. Arithmetic operator +,-,*,%,/

2. Assignment operator =

3. Comparison operator =,>,<,<>,>=,<=,!= (non-SQL-92 standard)

4. Logical operator And,or,not

Third, insert data

1. Inserting a single row of data

INSERT into table name (column name) values (value)

INSERT into Student (name,age,email) VALUES ("Zhang San", "[email protected]");

2. Insert multiple rows of data at once (build a new table in advance)

INSERT into Student (name, address, email)

SELECT Name,address,email

From School

3. Add data from an existing table to a new table (a new table is created directly at query time)

SELECT Student.name,student.email

Into Adderss

From Student

4. Merge data with Union keyword to insert

INSERT Student (Name,email)

SELECT ', ' UNION

SELECT ', ' UNION

SELECT ', '

Last line cannot be added to Union

Iv. Updating of data

Update table name set column name = update value WHERE update condition

Example: UPDATE Student

SET name= ' Zhang San ' WHERE id=1

V. Deletion of data

Delete a single row of data

DELETE from table name WHERE condition

DELETE from Student where Name= ' Zhang San '

Delete all rows in a table

Trucate TABLE Student

Table structure, columns, constraints, indexes do not change, cannot be used for tables with foreign KEY constraints, use Delete


The Nineth Chapter data query basis

First, the statement query

Syntax: SELECT column Name

From table name

WHERE condition

Column name for order by sort [ASC or DESC]

1. Querying all data rows and columns

SELECT * from Student

2. Querying some columns or rows

SELECT scode,name,address

From Student

WHERE name= ' Zhang San '

3. Using the alias of a column in a query

SELECT name as student's name, email as student email

From Student

WHERE adress= ' Shanghai '

4. Querying for null values

SELECT name from Student WHERE e-mail is null

5. Using constant columns in queries

SELECT name =name, address =address, ' Shanghai One ' as school name

From Student

6 query returns the limit number of rows

SELECT TOP 5 Name,email

From Student WHERE sex=0

Or

SELECT TOP PERCENT Name,email

From Student WHERE sex=0

Second, the query uses the function p223-p224 page

1. String functions

2. Date function

3. Mathematical functions

4. System functions


The tenth Chapter fuzzy query and Aggregation function

One, wildcard characters

_ One character

% arbitrary length string

[] One character of the range specified in parentheses [1-5]

[^] Any character not in the range specified in parentheses [^1-2]

The like fuzzy query is used to match a string or part of a string

Iii. using between to query within a certain range

SELECT * from Student WHERE score between and 80

Iv. using in to query within enumeration values

SELECT Name,email

From Student WHERE address in (' Beijing ', ' Shanghai ')

Four, SUM () function

Returns the sum of all the values in an expression

SELECT SUM (Scores) from Scores WHERE studentid=23

V. AVG () function

Returns the average of all the values in the expression, the null value is ignored and can only be used for columns of numeric types

Six, MAX () function min () function

Returns the maximum value in an expression, min () returns the minimum value

Seven, COUNT () function

Returns a count of the provided group or Recordset, which can be used to remove any type of column other than Text,image,ntext

SELECT COUNT (*) from Student

The aggregate function returns a number



11th. Connecting Queries and group queries

First, use GROUP by group query

SELECT COUNT (*) as number, Sex from Student

GROUP by Sex

When using group BY, the columns you can specify in the select list are limited and allow only a few items:

1. Grouped columns

2. An expression that returns a value for each grouping, such as the column computed by the aggregate function

Iii. using hacing for group filtering

Where only the data before grouping statistics is filtered, the conditional filter after grouping must use having,having for grouping

Data to filter, and "group" as "column" to qualify the condition

Iv. having and where to use the order

WHERE---GROUP by---have

You cannot use aliases after GROUP by, and you cannot use aliases behind them.

ORDER by and where can use aliases

Six, internal connection query

There are two ways: 1. Specify the join condition in the WHERE clause

SELECT A.name,s.id,s.score

From student [as] a,scores [as] s

WHERE a.id=s.id

2. Using inner JOIN in from On

SELECT A.name,s.id,s.score

From student [as] a

INNER JOIN Scores [as] s on (a.id=s.id)

WHERE s.score>=60

3. Above three tables

SELECT s.name student name, CS. Coursename course name, C.score exam Results

From Student S

INNER JOIN score C on (S.scode=c.studentid)

INNER JOIN Course CS on (CS. Courseid=c.courseid)

Seven, outer connection query

Two ways: 1. Left outer connection

SELECT S.name,c.courseid,c.score

From Student S

Left OUTER joins score C on S.scode=c.studentid

2. Right outer connection

SELECT Cs.name,c.studentid,c.score

From Course CS

Rigth OUTER JOIN score C on CS. Coureseid=c.coureseid

Eight, the difference between internal and external connections:

The result of an inner join query is to pick the data that meets the join criteria from the combination of two or more tables, ignoring it if the data fails to meet the join criteria.

In an intra-connection, the table participating in the connection is equal in status.

Tables participating in a join in an outer join query have a master-slave divide each row of data in the primary table matches the data column from the table, returning data that meets the join criteria directly to the result set

The columns that do not meet the join criteria are filled with a null value (NULL) and then returned to the result set.


14th. Accessing the database using ADO

First, ADO. NET has a great advantage when it is disconnected from the data source and can use the data.

Second, ADO. NET two components: 1). NET Framework data providers are groups designed specifically for data processing and fast, forward-only, read-only access

Thing Use it to connect to a data source, execute commands, and retrieve results, and manipulate the data source directly.

2) datasets are specifically designed for data access independent of any data source. With it, you don't have to directly and the data source

Working with large amounts of data, you can also bind data to a control.

Iii. four core objects of a. NET Framework Data Provider

Connection establishing a connection to a specific data source

command to execute commands against the data source

DataReader read-only data stream from the data source

DataAdapter populating the DataSet with a data source and parsing the update

Iv. properties and methods of Connetion

Property: ConnectionString

Method: Open (); Opening a database connection

Close (); Turn off database connections

Establish connection: Sting str= "Data source= server name; Initial catalog= database name; User id= username; pwd= password ";

SqlConnection conn=new SqlConnection (str);

Conn. Open ();

Close connection: Conn. Close ();

V. Exception handling

try{}

catch{}

Shortcut key: Ctrl+k+s

Try

{

Conn. Open ();

}

catch (Exception ex)

{

Console.WriteLine (ex. message);//message encapsulates the error message

}

Finally

{

Conn. Close ();//actions that will be performed regardless of how

}

Vi. executing database operations with command objects

String Sql= "";//Operation performed

SqlCommand comm=new SqlCommand (SQL, conn);

Vii. Command method

1.int ExecuteNonQuery () executes statements that do not return rows, such as the number of rows affected by UPDATE return

2.SqlDateReader ExecuteReader () or Sqldatereader ExecuteReader (CommandBehavior behavior)

Executes the query command, returning the DataReader object. The latter in parentheses closes the database while closing the object

3.object ExecuteScalar () returns a single value, such as execution count (*)



The 15th chapter uses ADO to query and manipulate data

First, StringBuilder class

Common methods: 1) StringBuilder appendline (String str) appended at the end

StringBuilder sb=new Srtingbuilder ();

Sb. Appendline ("");

Sb. Apeendline ("");

...

2) StringBuilder AppendFormat (string format,object arg0,object arg1) to add a specific format string

3) StringBuilder Insert (int index,string str) inserts the specified string at the specified position

4) Remove (int starindex,int length) removes the specified string

If you want to convert a StringBuilder class object to a String class object, the only way is to use the ToString () method

Second, the use of DataReader objects

1. Create a Command object, call the Command object's Executedatareader () method, and return a DataReader object with the DataReader object

The Read () method reads a row of records that can be read by loop-by-clause

SqlDataReader Reader=comm. ExecuteReader ();

while (reader. Read ())

{

Console.WriteLine ("{0}\t{1}\t{2}\t", reader["id"],reader["name"],reader["email"]);

}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.