(keep track of your own review)
Concept
Simply understand the class used to connect to the database.
Work flow
The ①connection object is used to connect to the database.
Two ways to connect: Windows Authentication/SQL Server Authentication
Private voidButton1_Click (Objectsender, EventArgs e) { Try { //string Str = "Server=.;i Nitial catalog= "DB_PWMS"; integrated SECURITY=SSPI ";//Windows Authentication stringSTR ="server=.; Database="Db_pwms"; uid=sa;pwd=***"; // SQL Server Authentication //A string that declares the STR store connection database. //server=. Server name = Equals Local. //Initial catalog= "db_pwms" database name =db_pwms. SqlConnection conn=NewSqlConnection (STR);//declaring ObjectsConn. Open ();//Connect on if(Conn. State==connectionstate.open)//The State property is judged open or not{richTextBox1.Text="has been opened"; } } Catch{MessageBox.Show ("Connection Failed"); } }
The ②command object is used to manipulate the database. (Three important methods: ExecuteNonQuery (), ExecuteReader (), ExecuteScalar ())
⑴ Use the ExecuteNonQuery () method as an example of update (change data)
Private voidButton2_Click (Objectsender, EventArgs e) {SqlConnection conn=NewSqlConnection ("Server=.;i Nitial catalog=db_pwms;integrated Security=sspi"); Conn. Open ();//first, connect. Try{SqlCommand cmd=NewSqlCommand ();//instance action item cmdCmd. Connection = conn;//Operation Conn This databaseCmd.commandtext ="Update table_1 set prices =3333 where Origin = ' homemade '";//operation of such a sentence SQL statementCmd.commandtype = CommandType.Text;//The book is so written, do not know what to do, and later know. It's OK to get rid of this sentence. Cmd. ExecuteNonQuery ();//Command object One of the three important methods, perform additions and deletions to search inti =Convert.ToInt32 (cmd. ExecuteNonQuery ()); Label2. Text= i +"Data Changes"; } Catch(Exception ex) {MessageBox.Show (ex). Message); } }
Click events (Button2)
Pre-execution database
After execution
⑵ data in various poses executescalar ()
The aggregate function of this method
|
Description |
AVG () |
Average |
Count () |
There are several data |
Max () |
Maximum Value |
Min () |
Minimum value |
SUM () |
And |
Take count () and Max () as an example
Private void button3_click (object sender, EventArgs e) {
conn = new SqlConnection ("Server=.;i Nitial catalog=db_pwms;integrated Security=sspi ");
Conn. Open (); Try {
string S1 = "SELECT COUNT (2) from Table_1";//Number of Tables count ()
String s2 = "Select Max (prices) from Table_1";//prices Max ()
SqlCommand cmd = new SqlCommand (s1,conn);
SqlCommand cmd1 = new SqlCommand (s2,conn);
int i = Convert.ToInt32 (cmd. ExecuteScalar ()); // object to int type int j = Convert.ToInt32 (cmd1. ExecuteScalar ()); = i+" Strip data "; " The most expensive " + J; } Catch (Exception ex) {MessageBox.Show (ex). Message); } }
Ado. NET Basic Learning