vc# Database Programming 1

Source: Internet
Author: User
Tags bind count connect tostring zip
Programming | data | Database programming is always an important aspect of programming language and also a difficult problem. Database programming is very rich in content, but the most basic programming is a few, such as: Connect the database, get the required data and data records for browsing, delete, modify, insert and other operations. It also focuses on the data from the following data records. This article focuses on the basic programming of Visual C # databases: How to browse records, modify records, delete records, and insert records.



A Design and operation of the environment settings:



(1). Windows 2000 Server Edition



(2). Microsoft Data acess Component version 2.6 (MDAC 2.6)



(3). Net FrameWork SDK Beta 2



For a clearer explanation of the problem, the database is selected using the currently typical database, one is the local database Access 2000, and the other is the remote database SQL Server 2000. Where the local database name is "Db.mdb", in which a data table "person" is defined, and the data structure of the person table is the following table:



Field Name field Type field meaning

ID number ordinal

XM Text Name

XB Text Gender

NL text Age

Zip text zip code



The database server name for the remote database SQL Server 2000 is "Server1", the database name is "Data1", the login ID is "sa", the password is empty, and a "person" table is defined in the database, as shown in the data structure.

Two How to browse Data:



In Visual C # data binding, you've learned how to bind certain fields in a dataset to a property of the WinForm component, so that programmers can customize the form of data display based on the WinForm component. And the WinForm component display at this point can change as the record pointer changes. Thus, the key to browsing data logging is how to change the record pointer. To do this, you use the BindingManagerBase class, whose primary role is to manage objects that are implemented to bind to the same data source. Specifically, you can synchronize components on a Windows Form that have data binding to the same data source. A property "Position" is defined in the BindingManagerBase class to change the data pointer in the BindingManagerBase object. Creating a BindingManagerBase object must use the BindingContext class, in fact, each object that is inherited from the control class has a single BindingContext object. The BindingManagerBase object that implements the data-binding component in most creation forms is obtained using the BindingContext of the form class. The following code is a model of an Access 2000 database that is created with a BindingManagerBase object called "Mybind."



Create a OleDbConnection

String Strcon = "Provider = microsoft.jet.oledb.4.0;" Data Source = Db.mdb ";

OleDbConnection myconn = new OleDbConnection (Strcon);

String strcom = "SELECT * from person";

file://Create a DataSet

myDataSet = new DataSet ();



MyConn.Open ();

file://use OleDbDataAdapter to get a dataset

OleDbDataAdapter mycommand = new OleDbDataAdapter (strcom, myconn);

file://bind the dataset to the Books data table

Mycommand.fill (myDataSet, "person");

file://close this OleDbConnection

Myconn.close ();

Mybind = this. BindingContext [myDataSet, "person"];



The following code is modeled on a SQL Server 2000 database and creates a BindingManagerBase object called "Mybind."



Sets the data connection string, which means that the SQL Server database is opened, the server name is Server1, and the database is Data1

String Strcon = "Provider = sqloledb.1;" Persist security Info = False; User ID = sa; Initial Catalog = data1; Data Source = Server1 ";

OleDbConnection myconn = new OleDbConnection (Strcon);

MyConn.Open ();

String strcom = "SELECT * from person";

file://Create a DataSet

myDataSet = new DataSet ();

file://use OleDbDataAdapter to get a dataset

OleDbDataAdapter mycommand = new OleDbDataAdapter (strcom, myconn);

file://bind the dataset to the person datasheet

Mycommand.fill (myDataSet, "person");

file://close this OleDbConnection

Myconn.close ();

Mybind = this. BindingContext [myDataSet, "person"];



The BindingManagerBase object that is the same data source is obtained, by changing the "Position" property value of this object, so that the data of the component that binds the data changes accordingly, thus realizes the navigation data record.



< I >. Navigation Button "Previous" Implementation method:



protected void Goprevious (object sender, System.EventArgs e)

{

if (mybind.position = 0)

MessageBox.Show ("It's the first record!") "," Information tips! ", MessageBoxButtons.OK, MessageBoxIcon.Information);

Else

Mybind.position-= 1;

}



< II >. Navigation Button "Next" Implementation method:



protected void GoNext (object sender, System.EventArgs e)

{

if (mybind.position = = mybind.count-1)

MessageBox.Show ("It's the last record!") "," Information tips! ", MessageBoxButtons.OK, MessageBoxIcon.Information);

Else

Mybind.position + 1;

}



< III >. Navigation button "to tail" implementation method:



protected void Golast (object sender, System.EventArgs e)

{

Mybind.position = mybind.count-1;

}

< IV >. Navigation Button "to first" implementation method:

protected void Gofirst (object sender, System.EventArgs e)

{

mybind.position = 0;

}



Note: "Count" is another important property of the BindingManagerBase object and is the total number of data set records.



Three Implementation of delete records: </P><P> in the operation of data records, there are two points must be very clear: </P><P> first: In the data record operation, I think some programmers must have such a doubt, When a dataset is requested on the database server, a "DataSet" object is generated to manage the dataset, so that if the request to the database server is very large, there will also be a lot of "dataset" objects that will inevitably cause the database server to crash. This idea is natural, but it does not match the reality, because the DataSet object is not generated on the server side, but on the client. Therefore, the impact on the database server is not very large when confronted with many requests for data. </P><P> Second: Remember to write a three-tier data model with Delphi, every time the changes to the database is in fact only the first layer of data generated by the changes, to really modify the database, you must also call a different method. While processing a database with ado.net, while the direct object being processed is a database, the content in the DataSet object is not changed, and the data component that is being displayed is derived from the DataSet object, which creates an illusion Is that the modified record has not been modified, the deleted records are not deleted. Therefore, when the data recording operation, after the database is modified, the "DataSet" object to make the necessary changes, so as to ensure that "dataset" object and the database content consistent, synchronized. The following code is the program code that deletes the record displayed by the current bound component, which is a template in the Access 2000 database: </p><p>protected void Delete_record (object sender, System.EventArgs e)

{

DialogResult r = MessageBox.Show ("Delete current record!") "," delete the current record! ", Messageboxbuttons.yesno, messageboxicon.question);

int ss = (int) r;

if (ss = 6)//press OK button

{

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 ();

String Strdele = "DELETE from person WHERE id=" + t_id. Text;

OleDbCommand mycommand = new OleDbCommand (Strdele, myconn);

file://deletes the specified record from the database

Mycommand.executenonquery ();

file://deletes the specified record from the dataset

mydataset.tables ["Person"]. Rows [Mybind.position]. Delete ();

mydataset.tables ["Person"]. AcceptChanges ();

Myconn.close ();

}

catch (Exception ed)

{

MessageBox.Show ("Delete logging error message:" + ed.) ToString (), "Error!" " ) ;

}

}

</P><P> The following code is the program code that deletes the records displayed by the current bound component, which is based on a SQL Server 2000 database, and differs only in data links: </P><P> protected void Delete_record (object sender, System.EventArgs e)

{

DialogResult r = MessageBox.Show ("Delete current record!") "," delete the current record! ", Messageboxbuttons.yesno, messageboxicon.question);

int ss = (int) r;

if (ss = 6)//press OK button

{

try{

Set the data connection string, meaning to open the SQL Server database, the server name is Server1, and the database is Data1

String Strcon = "Provider = sqloledb.1;" Persist security Info = False; User ID = sa; Initial Catalog = data1; Data Source = Server1 ";

OleDbConnection myconn = new OleDbConnection (Strcon);

MyConn.Open ();

String Strdele = "DELETE from person WHERE id=" + t_id. Text;

OleDbCommand mycommand = new OleDbCommand (Strdele, myconn);

file://deletes the specified record from the database

Mycommand.executenonquery ();

file://deletes the specified record from the dataset

mydataset.tables ["Person"]. Rows [Mybind.position]. Delete ();

mydataset.tables ["Person"]. AcceptChanges ();

Myconn.close ();

}

catch (Exception ed)

{

MessageBox.Show ("Delete logging error message:" + ed.) ToString (), "Error!" " ) ;

}

}

</P><P> in these two pieces of code, the "Datsset" object was modified as necessary while the database was being changed.

The following figure is the running interface for deleting data records in a program: </P><P>

  


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.