Sunteți pe pagina 1din 9

UsingSQLStoredProcedureswithVB.

NET
PostedbyHannesDuPreezonJune6th,2014
Tweet

Vote!

Share

Introduction
Amonthorsoago,IwroteafewarticlesintroducingyoutotheworldofdatabasesandVB.Ifyouhavefollowedthem,you
haveseenthatitisnotparticularlydifficulttousedatabasesproperlyfromVB.Today'sarticleisnoexception.TodayIwilltalk
aboutusingstoredproceduresbuiltintoSQLServer,withyourVB.NETprograms.

WhatareStoredProcedures?
Well,technically,hereisagreatdefinitionbut,astoredprocedureissimplyameansofkeepingyourdatabaselayerapart
fromyouractualprogram'scode.YoustorewhateverSQLcommandsyou'dliketoexecuteinastoredprocedurethatyoucan
useexternally.AnotherbenefitofastoredprocedureisthatiteliminatestheriskofSQLInjection,asalltheparametersused
willbepopulateddynamically.

WhatWillYouLearnToday?
BonitaBPM7:DeveloperfriendlyforEngagingApplications

DownloadNow

Todayyouwilllearnthefollowing:
Creatingadatabasetablewithastoredprocedure
Addingdatatothecreatedtableviaastoredprocedure
Editingdataviastoredprocedures
Deletingdatafromtableswithastoredprocedure
Deletingatableviaastoredprocedure
UsingalloftheabovefromVB.NET
Letusstart!

CreatingtheStoredProcedures
Beforewecancreateastoredproceduretodoalloftheabovementionedtasks,weobviouslyneedadatabase.Imaybe
captainobvioushere,butopenSQLServerandcreateanewdatabasenamedTest.Ifyoudonotwanttocreateadatabase,
leaveitatthedefaultSQLServerdatabase,whichisMaster.

CreateTableStoredProcedure
CreateanewSQLQueryandtypethefollowing:
CREATEPROCEDURECreateTable

AS

5. BEGIN

CREATETABLEtblSPExample(
StudentIDintIDENTITY(1,1),
Namevarchar(50)NOTNULL,
10. Surnamevarchar(50)NOTNULL,
AgeintNOTNULL,
PRIMARYKEY(StudentID))

END
ThiscreatesaprocedureinSQLnamedCreateTable.Thenittellstheprocedurewhattodo.ThisisastandardSQL
statementcreatingatablewiththefields,theirdatatypesandeachfield'sconstraints.

InsertIntoStoredProcedure
CreateanewSQLQueryandtypethefollowing:
CREATEPROCEDUREInsertDataIntoTable
@Namevarchar(50),
@Surnamevarchar(50),
@Ageint
5.
AS

BEGIN

10. INSERTINTOtblSPExample(Name,Surname,Age)

VALUES(@Name,@Surname,@Age)

15. END
BeforeyoucreatetheInsertstatement,youmustspecifytheparametersthatthisquerywillexpect.Theseparameterswillbe
populatedduringruntimeofyourapplication.

UpdateStoredProcedure
CreateanewSQLQueryandtypethefollowing:
CREATEPROCEDUREUpdateDataInsideTable
@Namevarchar(50),
@Surnamevarchar(50),
@Ageint,
5. @StudentIDint

AS

BEGIN

10.
UPDATEtblSPExample

SETName=@Name,Surname=@Surname,Age=@Age

15. WHEREStudentID=@StudentID

END

DeleteStoredProcedure
CreateanewSQLQueryandtypethefollowing:
CREATEPROCEDUREDeleteDataFromTable

@StudentIDint

5. AS

BEGIN

DELETEFROMtblSPExample
10.
WHEREStudentID=@StudentID

END

DropTableStoredProcedure
CreateanewSQLQueryandtypethefollowing:
CREATEPROCEDUREDropTable

AS

5. BEGIN

DROPTABLEtblSPExample

END

OurVB.NETProject
NowwecanmoveontocreatetheVB.NETproject.NameitanythingyoulikeanddesigntheformtoresembleFigure1.

Figure1OurDesign

Coding
Inallhonesty,mostofthecodeIwilldemonstratetodaywillbemoreorlessthesame.Ilivebytheprinciple:Keepitsimple
stupid.Thishasbroughtmeveryfar,evenifIamnotthesharpesttoolintheshed.
Asalways,letmestartwiththeImportsstatement(s)neededfortoday'sexample.Addthislineontopofyourclassdefinition:
ImportsSystem.Data.SqlClient'ImportSQLCapabilities
Now,createthemodularvariables:
PrivatestrConnAsString="DataSource=HANNES;InitialCatalog=Master;IntegratedSecurity=True"
PrivatesqlConAsSqlConnection

Thefirstobject,strConnspecifiesourdatabaseconnectionstring.Itisbrokendownintothreeparts:
1. Thedatabaseserver,whichinthiscaseiscalledHannes
2. ThedatabasenamewhichisMaster
3. Securitysettings
Thenextobject,sqlConwillbeusedasaSQLConnectionobject,whichassistsinconnectingtothephysicaldatastore
specifiedearlier.
Now,let'sgetthepartystarted!
Thisnextsubyouwillbecreatingisusedjusttoloadthedatafromthedatabaseanddisplayittotheuser.Thereisnouseof
astoredprocedureasthatwouldhavebeenoverkill.Addthissub:
PrivateSubLoadData()

DimstrQueryAsString

5. strQuery="SELECT*FROMtblSPExample"

sqlCon=NewSqlConnection(strConn)


Using(sqlCon)
10.
DimsqlCommAsSqlCommand=NewSqlCommand(strQuery,sqlCon)

sqlCon.Open()

15. DimsqlReaderAsSqlDataReader=sqlComm.ExecuteReader()

IfsqlReader.HasRowsThen

While(sqlReader.Read())
20.
txtName.Text=sqlReader.GetString(1)
txtSurname.Text=sqlReader.GetString(2)
txtAge.Text=sqlReader.GetValue(3)

25. EndWhile

EndIf

30. sqlReader.Close()

EndUsing

EndSub
Thisshouldlookfamiliarifyouhavereadmypreviousarticleconcerningdatabases.Ifyouhaven'treadanyofthemyet,here
isanintroductiontogetyoustarted.Anyways,itisquitesimplereally.ThisiswhathappenedintheLoadDatasub:
1. Icreatedastringobjecttohosttheultimatequerystring.
2. Istoredthequeryinsidetheobject.ThisqueryselectsallthedatafromthetblSPExampletable.Thistableyouwill
createlaterviatheStoredProcedureyoucreatedlater.
3. Iopentheconnectiontothedatabase.
4. Createdacommandobject.Thisobjectwillexecutethequery,toreturnthedesireddatatotheDataReader.
5. IftheDataReadercanidentifydata,itwillreturneachrowintotheassociatedtextboxes.
6. Iclosealltheconnectionstothedatabase.
CreatetheCreateTablesubnow:
PrivateSubCreateTable()

sqlCon=NewSqlConnection(strConn)

5.
Using(sqlCon)


DimsqlCommAsNewSqlCommand

10. sqlComm.Connection=sqlCon

sqlComm.CommandText="CreateTable"
sqlComm.CommandType=CommandType.StoredProcedure

15.
sqlCon.Open()

sqlComm.ExecuteNonQuery()

20. EndUsing

EndSub
It'sthesameprinciplehere,exceptthatwemodifytheCommandobjectalittletospecifythestoredprocedurewewillbe
usingthen,weexecuteitasaNonQuery.NonQuerymeansthatthereisnodatabeingreturned,justasimpleactiontheSQL
codeshouldtake.
Nowthatyouhaveatable,youcaninsertdataintoit.CreatetheInsertNewRecordsubnow:
PrivateSubInsertNewRecord()

sqlCon=NewSqlConnection(strConn)

5. Using(sqlCon)

DimsqlCommAsNewSqlCommand()

sqlComm.Connection=sqlCon
10.
sqlComm.CommandText="InsertDataIntoTable"
sqlComm.CommandType=CommandType.StoredProcedure

sqlComm.Parameters.AddWithValue("FirstName",txtName.Text)
15. sqlComm.Parameters.AddWithValue("Surname",txtSurname.Text)
sqlComm.Parameters.AddWithValue("Age",Integer.Parse(txtAge.Text))

sqlCon.Open()

20. sqlComm.ExecuteNonQuery()

EndUsing


25. LoadData()

EndSub
Again,stillfollowingthesameprinciplesee,Itoldyouitiseasy!Thereareacoupleofnewstatementsinthere.The
statementsinthemiddleaddparameterstothecommandobject.TheseparameterswerespecifiedinsidetheInsertStored
Procedure.ByusingparametersiteasiertomanagethedatabeingsentintotheSQLCommandobject.Here,youalsogave
eachparameteravalue,whichistheassociatedtextbox.
Nowaddthefollowingtwosubs.Onesubistoedittheinformationinsideadatabasetabletheotheristodeletecertain
information:
PrivateSubUpdateRecord()

sqlCon=NewSqlConnection(strConn)

5. Using(sqlCon)

DimsqlCommAsNewSqlCommand

sqlComm.Connection=sqlCon
10.

sqlComm.CommandText="UpdateDataInsideTable"
sqlComm.CommandType=CommandType.StoredProcedure

15. sqlComm.Parameters.AddWithValue("Name",txtName.Text)
sqlComm.Parameters.AddWithValue("Surname",txtSurname.Text)
sqlComm.Parameters.AddWithValue("Age",Integer.Parse(txtAge.Text))

sqlCon.Open()
20.
sqlComm.ExecuteNonQuery()

EndUsing

25. LoadData()

EndSub

PrivateSubDeleteRecord()
30.
sqlCon=NewSqlConnection(strConn)

Using(sqlCon)
35.
DimsqlCommAsNewSqlCommand

sqlComm.Connection=sqlCon

40. sqlComm.CommandText="DeleteDataFromTable"
sqlComm.CommandType=CommandType.StoredProcedure

sqlComm.Parameters.AddWithValue("StudentID",Integer.Parse(txtSearch.Text))

45.
sqlCon.Open()

sqlComm.ExecuteNonQuery()

50. EndUsing

LoadData()

EndSub
Thenextsubistodropadesireddatabasetablefromadatabase:
PrivateSubDropTable()

sqlCon=NewSqlConnection(strConn)

5.
Using(sqlCon)

DimsqlCommAsNewSqlCommand

10. sqlComm.Connection=sqlCon

sqlComm.CommandText="DropTable"
sqlComm.CommandType=CommandType.StoredProcedure

15.
sqlCon.Open()

sqlComm.ExecuteNonQuery()

20. EndUsing

EndSub

Verysimpleindeed,agree?

Conclusion
Asyoucansee,ifyouhavethebasicfundamentalsofdatabasedesignandVB.NET,youcancreateverypowerfulyetsmall
programstoextractandmanipulatedata.Obviously,thisisjustasmallexamplebutitcanbeusedinanymajorapplication.I
hopeyouhaveenjoyedthislittlearticle.Untilnexttime,cheers!

S-ar putea să vă placă și