Xu Xiang Visual C # Database Programming (ZT)

xiaoxiao2021-03-06  59

Transfer from author blog: http://blog.9cbs.net/xiaolong83/ About database programming, Microsoft provides a unified data object access model, called ADO in Visual Studio6.0, which is unified in .NET is ADO. Net, master ADO.NET is equal to the core of the database programming. For database programming is always an important part of the programming language, it is also a difficult point. The content of database programming is very rich, but the most basic programming is that, such as: connecting to the database, getting required data, browsing, deleting, modifying, and inserting data records. Among them, it is focused on the data operation of the data record. This article focuses on exploring the Visual C # database basic programming, namely: how to browse records, modify records, delete records, and insert records. One. Program design and running environment settings: (1). Window 2000 server version (2) .microsoft Data Acze Component 2.6 or more version (MDAC 2.6) (3) .. Net Framework SDK Beta 2 For more clear instructions, in the database On the selection, the currently a typical database is used, one is the local database Access 2000, and the other is the remote database SQL Server 2000. The local database name is "db.mdb" where the data structure of the data table "Person", "Person" table is as follows:

Field Name Field Type Field Meaning ID Digital Sequence XM Text Name XB Text Gender NL Text Age Zip Text Postal Code Remote Database SQL Server 2000 Database Server Name "Server1", Database Name "DATA1", login ID "SA" The password is empty, and a "Person" table is also defined in the database, the data structure is as follows. two. How to browse data: In "Visual C # Data Binding", you have learned how to bind some fields in the data set to an attribute of the WinForm component, so that the programmer can be customized according to the WinForm component. Data display form, and at this time, the WinForm component display content can change as the record pointer changes. At this time, it is visible that the key to browse data records is how to change the record pointer. To implement this operation, you should use the BindingManagerBase class. The main role of this class is to manage objects that implement the same data source. Specifically, it is possible to keep the components that have been bonded to the same data source on the Windows form to remain synchronized. A property "position" is defined in the BindingManagerBase class, and the data pointer in the BindingManagerBase object can be changed by this attribute. Creating a BindingManagerBase object must be used to use the BindingContext class, in which each object you have inherited by inheritance by the Control class has a single BindingContext object, and the BindingManagerBase object that implements the data binding component in most creation forms is using the FORM class. BindingContext is obtained. The following code is a BindingManagerBase object that is "MyBind" with the Access 2000 database as a model.

// Create a OleDbConnectionstring strCon = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = db.mdb"; OleDbConnection myConn = new OleDbConnection (strCon); string strCom = "SELECT * FROM person"; file: // create A DataSetMyDataSet = new dataset (); myconn.open (); file: // Get a data set with oleDbdataadapter = new oledbdataadapter (strcom, myconn); file: // Bind the DataSet Books Data Table MyCommand.Fill MyDataSet, "Person"); File: // Turn this OLEDBConnectionmyConn.close (); mybind = this.bindingContext [myDataSet, "Person"]; the following code is a model with SQL Server 2000 database, creating a name "mybind" BindingManagerBase object. / / Set the data connection string, this string means to open the SQL Server database, the server name is Server1, the database is Data1String strcon= "provike = SQLOLDB.1; PERSIST security info = false; user id = sa; initial catalog = DATA1; DATA SOURCE = Server1 "; OLEDBConnection myconn = new oledbconnection (strcon); myconn.open (); string strands =" select * from person "; file: // Create a DataSetMyDataSet = New DataSet (); file: / / OleDbDataAdapter a data set obtained by the OleDbDataAdapter myCommand = new OleDbDataAdapter (strCom, myConn); file: // bind the person data table dataset myCommand.Fill (myDataSet, "person"); file: // Close OleDbConnectionmyConn.Close ( ); mybind = this.bindingContext [MyDataSet, "Person"]; get the BindingManagerBase object of the same data source, by changing the "position" attribute value of this object, the data of the components of the binding data displayed, Thereby, navigation data records are implemented. . Navigation button "Previous" implementation method:

Protected void goprevious (object sender, system.eventargs e) {if (mybind.position == 0) MessageBox.show ("has reached the first record!", "Information Tips!", MessageBoxButtons.ok, MessageBoxicon.Information) Elsemybind.position - = 1;} . Navigation button "Next" implementation method: protected void gonext (object sender, system.eventargs e) {if (mybind.position == mybind.count -1) MessageBox. Show ("has arrived in the last record!", "Information Tips!", MessageBoxButtons.ok, MessageBoxicon.information; ElsemyBind.Position = 1;} . Navigation button "to the tail" implementation method:

Protected Void GoLast (Object Sender, System.EventAndargs E) {mybind.position = mybind.count - 1;} . Navigation button "to the first" implementation method: protected void gofirst (Object sender, system.eventargs e) { Mybind.position = 0;} Note: "Count" is another important property of the BindingManagerBase object, which is the total number of data set records. three. Implementation Removal Record: When the data record is operated, it must be very clear: one: When you operate on the data record, I think some programmers must have such a doubt, when requested data for the database server When the set, "DataSet" object will be generated to manage the data set, so if these requests for the database server are very much, there will be a lot of "DataSet" objects, and they will inevitably make the database server crash. . This idea is natural, but it is not practical, because the "dataset" object is not generated at the server, but is generated at the client. So in the face of numerous data requests, the impact on the database server is not very big. Two: Remember when writing a three-layer data model with Delphi, each time a change to the database is actually a modification of the data set generated by the second layer, and must actually modify the database, and must call an additional method. When using the ADO.NET to process the database, although the direct object is a database, the content in the "DataSet" object does not change, while the binding data component displayed is derived from the "DataSet" object. This will create an illusion, that is, the revised record does not modify, the recorded record does not delete it. Therefore, when you operate the data record, after modifying the database, you must make the necessary modifications to the "DataSet" object so that the "DataSet" object and the database content are consistent, synchronized. The following code is the program code that deletes the records displayed by the current binding component, which is template with the Access 2000 database:

protected void Delete_record (object sender, System.EventArgs e) {DialogResult r = MessageBox.Show ( "current record Delete!", "delete the current record!", MessageBoxButtons.YesNo, MessageBoxIcon.Question); int ss = (int) R; if (ss == 6) // Press the "OK" button {Try {file: // Connect to a database strCon = "provider = microsoft.jet.Oledb.4.0; data source = db.mdb"; OleDbConnection myConn = new OleDbConnection (strCon); myConn.Open (); string strDele = "dELETE fROM person WHERE id =" t_id.Text; OleDbCommand myCommand = new OleDbCommand (strDele, myConn); file: // deleted from the database Specifies myCommand.executenonQuery (); file: // Remove the specified record MyDataSet.Tables ["Person"]. Rows [mybind.position]. Delete (); myDataSet.tables ["person"]. Acceptchanges () Myconn.close ();} catch (exception ed) {messagebox.show ("Delete Record Error Message:" Ed.toTString (), "Error!");}} 4. Insert data record: Inserting a logging operation of the database and deleting a logging operation Basic idea is consistent, that is, inserting data into the database via ADO.NET, then the "DataSet" object is modified. The following code is to modify the current recorded code as the ACCESS 2000 database:

Protected void update_record (Object sender, system.eventargs e) {int i = mybind.position; try {file: // Connect to a database strcon = "provider = microsoft.jet.Oledb.4.0; data source = db.mdb "" Oledbconnection myconn = new oledbconnection (strcon); myconn.open (); mydataset.tables ["person"]. Rows [mybind.position]. BegineDit (); file: // From the database modified specified record string struct = "UPDATE PERSON SET XM = '" T_XM.Text ", XB ='" T_XB.Text ", NL =" T_NL.Text ", Zip =" T_Books.Text "Where id = T_ID.Text; OLEDBCommand MyCommand = New OLEDBCOMMAND (STRUPDT, MyConn); MyCommand.executenonQuery (); mydataset.tables ["Person"]. rows [mybind.position]. endedit (); mydataset.tables ["Person" ]. Acceptchange (); myconn.close ();} catch (exception ed) {messagebox.show ("Modify specified record error:" ed.tostring (), "Error!");} Mybind.position = i; } Due to the difference between SQL Server 2000 Data Record Modification and Access 2000 Data Record modification operation is only in different data links, the specific code can refer to the code in "Deleting Data Record", which is not available here. Fives. Insert data record: and the previous two operations are consistent in the idea, which is to first insert data into the database via ADO.NET, and then make the necessary modifications to the "DataSet" object. The following code is to insert a data record as a model as an Access 2000 database.

Protected void insert_record (Object sender, system.eventargs e) {try {file: // Determines if all fields are added, then add it, reverse the prompt IF (t_id.text! = "" && t_xm.text! = " "&& t_xb.text! =" "&& t_nl.text! =" "&& t_books.text! =" ") {string myconn1 =" provike = microsoft.jet.Oledb.4.0; data source = db.mdb "; OLEDBConnection Myconn = new oledbconnection (myConn1); myconn.open (); string strinsert = "INSERT INTO PERSON (ID, XM, XB, NL, ZIP) VALUES ("; Strinsert = T_ID.Text "; Strinsert = T_Xm.Text "','"; Strinsert = T_Xb.Text "" "; Strinsert = T_NL.Text ", "; Strinsert = T_Books.Text ") "; OLEDBCommand Instance, OLEDBCommand INST.EXECUTENONQUERY (); myconn.close (); mydataset.tables ["person"]. Rows [mybind.position]. beginedit (); mydataset.tables ["person"]. Rows [mybind .Position]. EndAst (); mydataset.tables ["person"]. Acceptchanges ();} else {messagebox.show ("must fill all field values!", "Error!");}} Catch (Exception ED) ) {MessageBox.show ("Save Data Record " Ed.tostring ()," error! ");}} The difference between the SQL Server 2000 database is inserted and the ACCESS 2000 database insertion record operation is only only for different data links. The specific code can refer to the code in" Deleting Data Record ", which is not Provided. Six. Visual C # database programming The main interface of the source code and program run: Master the above points, write a complete database programming program is very easy, below is the complete database programming of Visual C # Code (DATA01.CS), this code is designed with the Access 2000 database as a model, as follows:

using System; using System.Drawing; using System.ComponentModel; using System.Windows.Forms; using System.Data.OleDb; using System.Data; public class Data: Form {private System.ComponentModel.Container components = null; private Button lastrec; private Button nextrec; private Button previousrec; private Button firstrec; private TextBox t_books; private TextBox t_nl; private ComboBox t_xb; private TextBox t_xm; private TextBox t_id; private Label l_books; private Label l_nl; private Label l_xb; private Label l_xm; private Label l_id; private Label label1; private DataSet myDataSet; private Button button1; private Button button2; private Button button3; private Button button4; private BindingManagerBase myBind; public Data () {file: // connect to a database getConnected (); / / InitializeComponent (); file: // Remove the resources used in the program Protected {if (disposing) {if (component! = Null) { Components.dispose ();}} Base.Dispose (Disposing); public Main () {Application.run (New Data ());} public void getConnected () {try {file: // Create an OLEDBConnectionstring strcon = "provider = microsoft.jet.Oledb.4.0; data source = db.mdb" ; OleDbConnection myConn = new OleDbConnection (strCon); string strCom = "SELECT * FROM person"; file: // create a DataSetmyDataSet = new dataSet (); myConn.Open (); file: // get a data set with OleDbDataAdapter OleDbDataAdapter Mycommand = new oledbdataadapter (strcom, myconn); file: // binds DataSet Books Datase MyCommand.Fill (MyDataSet, "Person"); file: // Turn this OLEDBConnectionmyConn.Close ();} catch (Exception E) {MessageBox.show ("Connection Error!" E.toString (), "Error");

}}} private void initializationComponent () {file: // Add control, slight this.name = "data"; this.text = "Visual C # database programming!"; this.ResumeLayout (false); mybind = this.bindingContext [MyDataSet, "Person"];} protected void new_record (Object sender, system.eventargs e) {t_id.text = (mybind.count 1) .tostring (); t_xm.text = "; t_xb.text =" "; t_nl.text =" "; t_books.text =" ";} protected void insert_record (object sender, system.eventargs e) {try {file: // Decisive All fields are added, then add it, Tip IF (t_id.text! = "&& t_xm.text! =" && t_xb.text! = "&& t_nl.text! =" && t_books.text! = "") {String myconn1 = "provike Microsoft.jet.OleDb.4.0; data source = db.mdb "; OLEDBConnection myconn = new oledbconnection (myConn1); myconn.open (); string strinsert =" Insert Into Person (ID, XM, XB, NL, Zip) VALUES ("; Strinsert = T_ID.Text ", '"; Strinsert = t_xm.text " ""; strinsert = t_xb.text "" "; Strinsert = T_NL.Text ", " ; Strinsert = T_Books.Text ")"; OLEDBCOMMAND INST = New OLEDBCO Mmand (Strinsert, MyConn); inst.executenonquery (); myconn.close (); mydataset.tables ["person"]. Rows [mybind.position]. Beginedit (); mydataset.tables ["Person"]. Rows [ mybind.position]. Endedit (); mydataset.tables ["Person"]. acceptchange ();} else {messagebox.show ("must fill all field values! "," Mistake! ");

}}} catch (exception ed) {MessageBox.show ("Save Data Record" Ed.toTString (), "Error!");}}} protected void update_record (Object sender, system.eventargs e) {int i = mybind .Position; try {file: // Connect to a database string strcon = "provider = microsoft.jet.Oledb.4.0; data source = db.mdb"; OLEDBConnection myconn = new oledbconnection (strcon); myconn.open (); MyDataSet.Tables ["Person"]. Rows [mybind.position]. Beginedit (); file: // Modify the specified record from the database string strunt = "Update Person Set XM = '" T_XM.Text ", XB = '" t_xb.text ", nl = " t_nl.text ", zip = " t_books.text " where id = " t_id.text; oledbcommand mycommand = new OLEDBCOMMAND (STRUPDT, MyConn); MyCommand.executenonQuery (); mydataset.tables ["person"]. rows [mybind.position]. Endedit (); mydataset.tables ["person"]. acceptchange (); myconn.close ();} (Exception Ed); ) {MessageBox.show ("Modify Specify Record Error:" Ed.toTString (), "Error!");} Mybind.position = i;} protected void delete_record (Object Sender , System.Eventargs e) {DialogResult r = messagebox.show ("Do you delete the current record! "," Delete the current record! ", Messageboxbuttons.question; int s = (int)); if (ss == 6) // Press the" OK "button {Try {file: // Connect to a database strcon =" provider = Microsoft.jet.Oledb.4.0; data source = db.mdb "; OLEDBConnection myconn = new oledbconnection (strcon); myconn.open (); string strde =" delete from person where id = "

T_ID.Text; OLEDBCOMMAND MyCommand = New OLEDBCOMMAND (STRDELE, MyConn); file: // Remove the specified record MyCommand.executenonQuery () from the database; file: // Remove the specified record MyDataSet.Tables ["Person" from DataSet. Rows [mybind.position]. Delete (); mydataset.tables ["Person"]. Acceptchange (); myconn.close ();} catch (exception ed) {messagebox.show ("Delete Record error message: ED .Tostring (), "error!");}}} File: // button "Take record" object event program protected void Golast (Object sender, system.EventArgs e) {mybind.position = mybind.count - 1;} File: // Button "Next" Opcher Event Program Protected Void Gonext (Object Sender, System.EventArgs E) {if (MyBind.Position == MyBind.count -1) MessageBox.show ("has arrived in the last record!" , "Information Tips!", MessageBoxicon.information; elseMybind.position = 1;} file: // button "Previous" Object Event Protected VoidGrevious (Object Sender, System.EventArgs E) {IF (mybind.position == 0) MessageBox.show ("has arrived in the first record!", "Information Tips!", MessageBoxButtons.ok, MessageBoxicon.information; elseMybind.position - = 1;} file: // button "First Record" Object Event Program Pro TECTED VOID GOFIRST (Object sender, system.eventargs e) {mybind.position = 0;}} For program code with SQL Server 2000 database as model, just put data links in DATA01.CS, namely: string myconn1 = "provike = Microsoft.jet. OleDb.4.0; Data Source = DB.mdb "; change to:

String strcon = "provider = SQLOLEDB.1; PERSIST security info = false; user id = sa; initial catalog = data1; data source = server1"; Note: This data link represents the meaning of the SQL Server database, the server name is Server1, the database can get Visual C # to the SQL Server 2000 database for the SQL Server 2000 database for the completion source code. So this article is no longer available. Seven. Summary: Database programming is always a key points and difficulties in programming content. These operations described above are the most basic and most important content in database programming. Those complex programming is nothing more than a number of stacked plies. Author Blog:

http://blog.9cbs.net/xiaolong83/

转载请注明原文地址:https://www.9cbs.com/read-83657.html

New Post(0)