Sunday, December 16, 2018
'How to Connect a Database and Add/Update/Delete/Record\r'
'How to Connect to a Database and institute/ modify/ call off enter In this tutorial I pull up stakes explain to you on how to tie to an Access selective in puddleationbase and allow you to Add/Update/ blue-pencilàa usher. To fully understand these tutorials pleaseàtransferàthe origination tagàHow to Add/Update/ erase Record using MS Access Database. This source code is part of theàHotel Reservation Systemàthat I am currently working. At the end of this tutorial you leave alone nobble the basic of database course of studying. I would like, however, to mark peculiarly for beginners that one way to adopt scheduleming is to sleep with how to debug a program and intent some of your conviction to reading.Dont be frightened on how short or long an article should be. The Copernican is at the end of the tutorial you w sorrow learn something NEW! If you already know the proposition, because fall apartââ¬â¢t bother to study this again. Table of co ntent 1. Introduction 2. letââ¬â¢s get started 3. Database inter-group communication 4. Add and Update a Record 5. wipe out a Record 6. Final Thoughts Introduction in the first place I started learning VB. NET one of the topic that I search for in the inter web is on how to merge to the database and make some changes to the table. Although thereââ¬â¢s a lot of results, but I cannot bring forth one that suit to my motivations.Most of the tutorial is using allure and drop features of vb. net tailoror. Well, this is okay in just about cases but what if youââ¬â¢d like to manipulate the data by code? So, I created this tutorial so that beginner programmer go forth learn from this. Letââ¬â¢s get started It is very alpha that you use your common sense to understand the logic of database program. thereââ¬â¢s a lot of features built-in to opthalmic Basic Editor that most programmer especially beginner who overlook it. One of the favorite tools I usually used is theàDEBUGGER. If you only knew how serious a debugger is, thence you do not even motivation to study this tutorial.Why? Because you can jump right forward to the source code and start firing the F8 financial statement from your severalizeboard and analyze every suck up as you spirit through the code. Anyway beginner is a beginner. You contract to start from scratch. If you founder already downloaded the source code, then open it in the visual basic . net editor by two-fold clicking the ââ¬Å"HowtoAddUpdateDeleteRecord. slnââ¬Â. If you want to know what is the inclination that runs the first time you start the program (by pressing F5) then double click the ââ¬Å"My strayââ¬Â at the Solution Explorer. Look at the inaugural Form.You will see that the value is ââ¬Å"frm nodesListââ¬Â. Now, click this object in the Solution Explorer and click the keep an eye on Code at the toolbar. Look for the incumbrance military issue similar at a lower place: secretà  molaràfrmCustomersList_Load(ByValàvectoràAsàSystem. Object,àByValàeàAsàSystem. EventArgs)HandlesàMyBase. Load àààààààsSql =àââ¬Å" assign CustomerID, CompanyName, ContactName, ContactTitle, Address FROM Customers ORDER BY CustomerID ASCââ¬Â ààààààààCallàFillList() FillListView(lvList, GetData(sSql)) destructionàstand in frmCustomersList_Load is the second unconscious process that runs when you hit the F5 winder from your keyboard.If youââ¬â¢d like to know how this code is penalise then press F8. Believe it or not F8 is the answer to all your programming question. And I rightfully mean it. When I started programming all I do is to search for free source code and start using the debugging tool. Thatââ¬â¢s why optic Basic is being named as Rapid finish Development or RAD. If you follow the debugger the first bank bill it executes is theàPrivateàhitmanàfrmCustomersList_Resi ze(ByValàsenderAsàObject,àByValàeàAsàSystem. EventArgs)àthen followed byàfrmCustomersList_Loadàwhich is actually the important mapping to broadsheet here.Another important debugging tool is ââ¬Å" on-off switch Breakpointââ¬Â. You will be prompted to your code if one of the line is marked by toggle break point. This can be through with(p) by pressing the F9 key or clicking the rectify menu then Toggle Breakpoint. This tool is important if the form is already loaded and you want to piece of ground the execution of a code say inwardly a command sack. For ex angstromle. Open the formàfrmCustomersListàand double click the make up button and move the up arrow key once and press F9. You willl be in possession of a picture as shown below: [inline:Toggle Breakpoint. jpg]Now, when you run the program and click the Add button you will be directed to the code editor window. This case you will see what is happening when you ar executing the progra m. Isnââ¬â¢t it nice? Database Connection In order to connect to the database you need a society string like this: realityàConstàcn rangeàAsàpull inà=àââ¬Å"Provider=Microsoft. Jet. OLEDB. 4. 0;Persist Security data=False;Data Source=.. /data/s adeninele. mdbââ¬Â accordingly open it by using this command: lightheadedàcnHotelàAsàOleDbConnection cnHotel =àNewàOleDbConnection WithàcnHotel Ifà. enjoin = ConnectionState.OpenàThenà. Close() .ConnectionString = cnString .Open() kiboshàWith You need this whether you useàOleDbDataReader, ExecuteNonQuery or OleDbCommandBuilderàto read or write into the database table. To know more about this single out just click this command and press F1 key to open the help files. Be sure you installed the MSDN. Since you have already open the contact to your database this is now the time to fill the ListView with data. This can be through by calling a function like: FillListView(lvList, GetData(sSql)) The line of code will then execute a function: Fill ListView control with data Publicàstep inàFillListView(ByRefàlvListàAsàListView,àByRefàmyDataàAsàOleDbDataReader) ààààààààdismalàitmListItemàAsàListViewItem DimàstrValueàAsàString DoàeyepatchàmyData. Read itmListItem =àNewàListViewItem() strValue = IIf(myData. IsDBNull(0),àââ¬Å"ââ¬Â, myData. GetValue(0)) àààààààààààitmListItem. school text = strValue ForàshtCntr = 1àToàmyData. FieldCount() â⬠1 ààààààààààààààààIfàmyData. IsDBNull(shtCntr)àThen àààààààààààààààààààitmListItem. cuneusItems. Add(ââ¬Å"ââ¬Â) ààààààààààààààààElse itmListItem. SubItems. Add(myData. GetString(shtCntr)) Ã Ã Ã Ã Ã Ã Ã Ã Ã Ã à  Ã Ã Ã Ã Ã finisàIf followingàshtCntr lvList. Items. Add(itmListItem) Loop EndàSub Again in order to see how this code is being put to death just run the program using the debugging tool (either F8 or F9). The rest of the procedure is executed only when they are called. For example, the code below is executed only when you click the Add button. PrivateàSubàbtnAdd_ piffle(ByValàsenderàAsàSystem. Object,àByValàeàAsàSystem. EventArgs)àHandlesbtnAdd. Click ààààààààDimàCustomerIDàAsàString frmCustomers. State = gModule. FormState. adStateAddMode ààààààààForàEachàsItemàAsàListViewItemàInàlvList.SelectedItems àààààààààààCustomerID = sItem. text edition beside frmCustomers. CustomerID = CustomerID frmCustomers. ShowDialog() CallàFillList() EndàSub This code will open the formàfrmCustomersàin convey agency and will e xecute also its own Load Event. If you want to open the formàfrmCustomersàin edit mode, then just double click the stage in a ListView. The code being executed are: PrivateàSubàlvList_DoubleClick(ByValàsenderàAsàObject,àByValàeàAsàSystem. EventArgs)àHandleslvList. DoubleClick ààààààààDimàCustomerIDàAsàString ForàEachàsItemàAsàListViewItemàInàlvList.SelectedItems àààààààààààCustomerID = sItem. text withstand Next WithàfrmCustomers .State = gModule. FormState. adStateEditMode ààààààààààà. CustomerID = CustomerID .ShowDialog() CallàFillList() EndàWith frmCustomers =àNothing EndàSub The two procedure seems carry the same concept, by opening a form, except they vary on the button invoke for execution. The line frmCustomers. State = gModule. FormState. adStateAddMode will tell the target form to open the connection to t he database in add mode and frmCustomers. State = gModule. FormState. adStateEditMode ill open the database in edit mode. Add and Update a Record Now, how to save the data in textboxes within the form? This can be done by calling a procedure calledbtnSave_Click. This procedure is fired when the Save button is clicked. PrivateàSubàbtnSave_Click(ByValàsenderàAsàSystem. Object,àByValàeàAsàSystem. EventArgs)àHandlesbtnSave. Click ààààààààDimàdtàAsàDataTable = dsCustomers. Tables(ââ¬Å"Customersââ¬Â) ààààààààIfàtxtCustomerID. textbook =àââ¬Å"ââ¬ÂàOràtxtCompanyName. school text =àââ¬Å"ââ¬ÂàThen àààààààààààMsgBox(ââ¬Å" divert fill up Customer ID or Company Name information. ââ¬Å", MsgBoxStyle.Critical) ààààààààààààExitàSub EndàIf Try IfàState = gModule. FormState. adStateAddModeàThen à  Ã Ã Ã Ã Ã Ã Ã Ã Ã Ã Ã Ã Ã Ã Ã ââ¬Ë add a row DimànewRowàAsàDataRow newRow = dt. NewRow() newRow(ââ¬Å"CustomerIDââ¬Â) = txtCustomerID. Text àààààààààààààààdt. Rows. Add(newRow) EndàIf Withàdt .Rows(0)(ââ¬Å"CustomerIDââ¬Â) = txtCustomerID. Text ààààààààààààààà. Rows(0)(ââ¬Å"CompanyNameââ¬Â) = txtCompanyName. Text ààààààààààààààà. Rows(0)(ââ¬Å"ContactNameââ¬Â) = IIf(txtContactName. Text =àââ¬Å"ââ¬Â, System. DBNull. Value, txtContactName. Text) ààààààààààààààà. Rows(0)(ââ¬Å"ContactTitleââ¬Â) = IIf(txtContactTitle. Text =àââ¬Å"ââ¬Â, System.DBNull. Value, txtContactTitle. Text) ààààààààààààààà. Rows(0)(ââ¬Å"Addressââ¬Â) = IIf(txtAddress. Text =àââ¬Å"ââ¬Â, Syste m. DBNull. Value, txtAddress. Text) ààààààààààààààà. Rows(0)(ââ¬Å"Cityââ¬Â) = IIf(txtCity. Text =àââ¬Å"ââ¬Â, System. DBNull. Value, txtCity. Text) ààààààààààààààà. Rows(0)(ââ¬Å" portionââ¬Â) = IIf(txtRegion. Text =àââ¬Å"ââ¬Â, System. DBNull. Value, txtRegion. Text) ààààààààààààààà. Rows(0)(ââ¬Å"PostalCodeââ¬Â) = IIf(txtPostalCode. Text =àââ¬Å"ââ¬Â, System. DBNull. Value, txtPostalCode. Text) ààààààààààààààà. Rows(0)(ââ¬Å"Countryââ¬Â) = IIf(txtCountry. Text =àââ¬Å"ââ¬Â, System. DBNull. Value, txtCountry.Text) ààààààààààààààà. Rows(0)(ââ¬Å"soundââ¬Â) = IIf(txtPhone. Text =àââ¬Å"ââ¬Â, System. DBNull. Value, txtPhone. Text) ààààààààààààààà. Rows(0)(â⠬Å"Faxââ¬Â) = IIf(txtFax. Text =àââ¬Å"ââ¬Â, System. DBNull. Value, txtFax. Text) àààààààààààààààdaCustomers. Update(dsCustomers,àââ¬Å"Customersââ¬Â) àààààààààààààààMsgBox(ââ¬Å"Record successfully saved. ââ¬Å", MsgBoxStyle. Information) ààààààààààààEndàWith CatchàexàAsàOleDbException MsgBox(ex. ToString) EndàTry EndàSub The code for adding and update a table is the same except that if you are in add mode you just evidently add this command: IfàState = gModule.FormState. adStateAddModeàThen ââ¬Ë add a row DimànewRowàAsàDataRow newRow = dt. NewRow() newRow(ââ¬Å"CustomerIDââ¬Â) = txtCustomerID. Text dt. Rows. Add(newRow) End If This way you do not need to create a separate command to cut-in and update a table. Delete a Record Let us go back toàfrmCustomersListàform and delete a record. The procedure before will be fired after clicking a Delete button: PrivateàSubàbtnDelete_Click(ByValàsenderàAsàSystem. Object,àByValàeàAsàSystem. EventArgs)àHandlesbtnDelete. Click ààààààààDimàCustomerIDàAsàString ForàEachàsItemàAsàListViewItemàInàlvList.SelectedItems àààààààààààCustomerID = sItem. Text Next IfàCustomerID ;;àââ¬Å"ââ¬ÂàThen ââ¬ËDelete the selected record DimàstrDeletedàAsàBoolean strDeleted = ExecNonQuery(ââ¬Å"DELETE Customers. CustomerID FROM Customers WHERE CustomerID= ââ¬Ëââ¬Âà& CustomerID &àââ¬Å"ââ¬Ëââ¬Â) ààààààààààààIfàstrDeleted =àââ¬Å"Trueââ¬ÂàThen MsgBox(ââ¬Å"Records deleted. ââ¬Å", MsgBoxStyle. Information) ààààààààààààààààCallàFillList() Else MsgBox(strDeleted) EndàIf Else MsgBox(ââ¬Å" Please select record to delete. ââ¬Å", MsgBoxStyle. Critical) ààààààààEndàIf EndàSub The important line here is the strDeleted = ExecNonQuery(ââ¬Å"DELETE Customers.CustomerID FROM Customers WHERE CustomerID= ââ¬Ëââ¬Âà& CustomerID &àââ¬Å"ââ¬Ëââ¬Â) which call the functionàExecNonQueryàand deletes a record based on the SQL Statement. Final Thoughts The above tutorial will simply teach you on how to connect to a database and make some changes to the database table. It is very important that you read first some tutorials about programming before you dive into the source code if youââ¬â¢re just starting out. If you really wanted to learn faster, then I recommend a book which is my reference also with this article. This book is calledàBeginning VB 2008 Databases: From initiate to Professional (Beginning:\r\n'
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment