Wednesday, August 14, 2019
How to Connect a Database and Add/Update/Delete/Record
How to Connect to a Database and Add/Update/Delete Record In this tutorial I will explain to you on how to connect to an Access database and allow you to Add/Update/Deleteà  a record. To fully understand these tutorials pleaseà  downloadà  the source codeà  How to Add/Update/Delete 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 will learn the basic of database programming. I would like, however, to emphasize especially for beginners that one way to learn programming is to know how to debug a program and devote some of your time to reading.Don't be frightened on how short or long an article should be. The important is at the end of the tutorial you will learn something NEW! If you already know the topic, then donââ¬â¢t bother to study this again. Table of Contents 1. Introduction 2. Letââ¬â¢s get started 3. Database Connection 4. Add and Update a Record 5. Delete a R   ecord 6. Final Thoughts Introduction Before I started learning VB. NET one of the topic that I search for in the internet is on how to connect to the database and make some changes to the table. Although thereââ¬â¢s a lot of results, but I cannot find one that suit to my needs.Most of the tutorial is using drag and drop features of vb. net editor. Well, this is okay in most cases but what if youââ¬â¢d like to manipulate the data by code? So, I created this tutorial so that beginner programmer will learn from this. Letââ¬â¢s get started It is very important that you use your common sense to understand the logic of database programming. Thereââ¬â¢s a lot of features built-in to Visual 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 important a debugger is, then you do not even need to study this tutorial.Why? Because you can jump right away to the source code and start    firing the F8 command from your keyboard and analyze every line as you step through the code. Anyway beginner is a beginner. You need to start from scratch. If you have already downloaded the source code, then open it in the visual basic . net editor by double clicking the ââ¬Å"HowtoAddUpdateDeleteRecord. slnâ⬠. If you want to know what is the object that runs the first time you start the program (by pressing F5) then double click the ââ¬Å"My Projectâ⬠ at the Solution Explorer. Look at the Startup Form.You will see that the value is ââ¬Å"frmCustomersListâ⬠. Now, click this object in the Solution Explorer and click the View Code at the toolbar. Look for the Load event similar below: Privateà  Subà  frmCustomersList_Load(ByValà  senderà  Asà  System. Object,à  ByValà  eà  Asà  System. EventArgs)Handlesà  MyBase. Load à  Ã  Ã  Ã  Ã  Ã  Ã   sSql =à  Ã¢â¬Å"SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address FROM Customers ORDER BY Cu   stomerID ASCâ⬠ à  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Callà  FillList() FillListView(lvList, GetData(sSql)) Endà  Sub frmCustomersList_Load is the second procedure that runs when you hit the F5 Key from your keyboard.If youââ¬â¢d like to know how this code is executed then press F8. Believe it or not F8 is the answer to all your programming question. And I really 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 Visual Basic is being named as Rapid Application Development or RAD. If you follow the debugger the first line it executes is theà  Privateà  Subà  frmCustomersList_Resize(ByValà  senderAsà  Object,à  ByValà  eà  Asà  System. EventArgs)à  then followed byà  frmCustomersList_Loadà  which is actually the important procedure to note here.Another important debugging tool is ââ¬Å"Toggle Breakpointâ⬠. You will be prompted to your code if one of the line is marked by toggle brea   k point. This can be done by pressing the F9 key or clicking the Debug menu then Toggle Breakpoint. This tool is important if the form is already loaded and you want to tract the execution of a code say within a command button. For example. Open the formà  frmCustomersListà  and double click the add button and move the up arrow key once and press F9. You willl have 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 are executing the program. Isnââ¬â¢t it nice? Database Connection In order to connect to the database you need a connection string like this: Publicà  Constà  cnStringà  Asà  Stringà  =à  Ã¢â¬Å"Provider=Microsoft. Jet. OLEDB. 4. 0;Persist Security Info=False;Data Source=.. /data/sample. mdbâ⬠ Then open it by using this command: Dimà  cnHotelà  Asà  OleDbConnection cnHotel =à  Newà  OleDbConnect   ion Withà  cnHotel Ifà  . State = ConnectionState.Openà  Thenà  . Close() .ConnectionString = cnString .Open() Endà  With You need this whether you useà  OleDbDataReader, ExecuteNonQuery or OleDbCommandBuilderà  to read or write into the database table. To know more about this class 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 connection to your database this is now the time to fill the ListView with data. This can be done by calling a function like: FillListView(lvList, GetData(sSql)) The line of code will then execute a function: Fill ListView control with data Publicà  Subà  FillListView(ByRefà  lvListà  Asà  ListView,à  ByRefà  myDataà  Asà  OleDbDataReader) à  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Dimà  itmListItemà  Asà  ListViewItem Dimà  strValueà  Asà  String Doà  Whileà  myData. Read itmListItem =à  Newà  ListViewItem() strValue = IIf(myData. IsDBNull(0),à  Ã¢â¬Å"â⬠,    myData. GetValue(0)) à  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã   itmListItem. Text = strValue Forà  shtCntr = 1à  Toà  myData. FieldCount() ââ¬â 1 à  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ifà  myData. IsDBNull(shtCntr)à  Then à  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã   itmListItem. SubItems. Add(ââ¬Å"â⬠) à  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Else itmListItem. SubItems. Add(myData. GetString(shtCntr)) à  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Endà  IfNextà  shtCntr lvList. Items. Add(itmListItem) Loop Endà  Sub Again in order to see how this code is being executed 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_Click(ByValà  senderà  Asà  System. Object,à  ByValà  eà  Asà  S   ystem. EventArgs)à  HandlesbtnAdd. Click à  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Dimà  CustomerIDà  Asà  String frmCustomers. State = gModule. FormState. adStateAddMode à  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Forà  Eachà  sItemà  Asà  ListViewItemà  Inà  lvList.SelectedItems à  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã   CustomerID = sItem. Text Next frmCustomers. CustomerID = CustomerID frmCustomers. ShowDialog() Callà  FillList() Endà  Sub This code will open the formà  frmCustomersà  in add mode and will execute also its own Load Event. If you want to open the formà  frmCustomersà  in edit mode, then just double click the item 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 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 the 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à  d   tà  Asà  DataTable = dsCustomers. Tables(ââ¬Å"Customersâ⬠) à  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ifà  txtCustomerID. Text =à  Ã¢â¬Å"â⬠à  Orà  txtCompanyName. Text =à  Ã¢â¬Å"â⬠à  Then à  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã   MsgBox(ââ¬Å"Please 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 =à  Ã¢â¬Å"â⬠, System. DBNull. Value, txtAddress. Text) à  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã   . Rows(0)(ââ¬Å"Cityâ⬠) = IIf(txtCity. Text =à  Ã¢â¬Å"â⬠, System. DBNull. Value, txtCity. Text) à  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã  Ã   . Rows(0)(ââ¬Å"Regionâ⬠) = 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)(ââ¬Å"Phoneâ⬠) = 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 u   pdating a table is the same except that if you are in add mode you just simply 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 insert 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(ââ¬Å"Record's 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 Novice to Professional (Beginning:    
Subscribe to:
Post Comments (Atom)
 
 
No comments:
Post a Comment