C H A P T E R  16

Connecting via Code

If you defined yourself as a pure database developer, you would only be writing T-SQL code building on your knowledge gained within this book. However, some DBAs write code outside of the database to access data and execute stored procedures, as well as many other tasks. This can be accomplished in many different programming languages and tools. The aim of this chapter is to demonstrate how you can connect to SQL Server and accomplish working with your data using Excel VBA, .NET, and Java, as these are the most common coding platforms that you are likely to use. To be clear, the aim of this chapter is not to make you an expert or even quite proficient in these languages or tools but to demonstrate basic code that provides you with a good start to expand on via Apress books or other media.

Each development tool has its own section, allowing you to jump straight to the relevant code you want to see an example of and where you will see the ApressFinancial database accessed and data displayed in console output. It will be assumed that each tool has been installed on your computer, although there will be links on my web site, www.fat-belly.com, to the software used within the book, or if there is a later relevant version of the software that should be used, post-publication of this book. Although there will be one example of working with the data in each language within this chapter, every example demonstrated will be available in every language from my web site and with the source code for this book.

Connecting to SQL Server can be achieved using the techniques and methods that have been described throughout the book so far. SQL Server Management Studio is a tool written using a development language and provides the techniques of connecting via Windows authentication or SQL Server authentication, which then uses role techniques to allow and restrict what you can do. To this end, you could conceivably rewrite SSMS in one of many languages that you will see demonstrated.

Before you get started in this chapter, there is one point I want to make clear. In each of the tools, there are different ways you can achieve the same goal that is being demonstrated. From Excel through to Java, there is more than one method to connect and work with SQL Server. However, what I demonstrate in each section is what I have personally found to be the best and the most common method that is used for that technology and a good basis to start your development from. If you use or find a different method that suits you better, I am happy to hear from you, and I can investigate putting alternatives on my web site. However, these examples will be perfect for getting any developer up and running but also provide a good base to progress. In this chapter, you will learn the following:

  • General application security
  • Working with Excel using the Data ribbon and then using VBA
  • Using Visual Studio to build a VB.NET and C# console application
  • Developing a solution using Eclipse, Java, and the SQL Java JDBC driver

The first step is to look at general application security.

General Application Security

Throughout the book, you have worked through examples of security and how you should consider and implement different security measures, ensuring that your database is secured from inadvertent or rogue access. Measures include authentication, roles, object permissions, and schemas. It is useful to summarize a few of the points again so that they are fresh in your mind while developing an application and so that any areas missed can be addressed.

The first area would be to ensure that a Windows group exists purely for accessing the server and database. You can then use this group for application-specific access to the correct objects. Bear in mind that your database solution may have more than one application connecting to it. This could include a GUI-based solution for administrative tasks and an Excel solution built to retrieve data for ad hoc reporting by some users. Having two Windows groups allows permissions to be defined specifically for each application’s needs, one for modification access and one for read-only reporting access.

You should also consider having and using an application role within the database, as discussed in Chapter 4.

Building stored procedures or views to retrieve and update the data that will retrieved by the application and grant execute permissions to these objects only to the Windows group or specific individuals if you are using SQL Server authentication will protect the data. If a report is built from data of a highly sensitive nature, then you may wish to give permission for the stored procedure or view to a specific individual to give the necessary granularity.

Some applications will build ad hoc T-SQL dependent on options selected or other criteria that are defined within its code. The T-SQL-built code is then verified within the application to ensure that it does not contain an SQL injection and is passed to the database for execution. This does not fit into the stored procedures or views model, and you therefore need to ensure that the most granular level of access is defined to give this login the minimum rights required to achieve its goal. Although the easiest and quickest way to provision SQL server is to allow all levels of permissions to all users, this is actually the biggest mistake you can make.

An SQL injection is where ad hoc SQL is built within an application legitimately, but someone has appended or replaced their own SQL via some area that allows user-entered information. This can happen via several methods, but one method is where an application has a user-entry field and a value from that field is used as part of the query, quite often used as part of the WHERE clause. If someone entered T-SQL code that would complete the WHERE clause in the user-entry field that performed an UPDATE or DELETE, then this is where an SQL injection has occurred; someone has injected destructive SQL into your SQL.

All of these security areas are database-based, but one area of security that is important is to hide the connection details of the application’s connection to your database. This can be achieved via basic or complex encryption of the details. Windows authentication does reduce the need to encrypt details, as this is quite a secure method, but if you offer mixed-mode authentication, then you must encrypt any database user and password you use. There is example code on my web site, which you can use to encrypt and decrypt a password, along with instructions on what you should change to ensure that the encryption values are secure for you. The main point is that you should never store connection details anywhere as clear text. The details within the book are clear text for ease of reading, although they are invalid outside the scope of this book.

image Caution Do as I say, not as I do.

Now that the main security items have been refreshed and new application security issues addressed that need to be considered when developing an application, it’s time to look at connecting to your data via different methods.

Connecting with Excel or Excel Visual Basic for Applications (VBA)

The simplest and quickest tool in this chapter to access your data is Excel. By completing a handful of clicks, you can connect to your database, choose a specific table, or execute a stored procedure, and the data will be returned and placed within an Excel workbook and data displayed ready to send out. This is why Excel is a quick and easy tool and used by so many users and developers for reporting purposes.

You can connect to SQL Server using several methods, but the two that this chapter will concentrate on are through the Data ribbon and Visual Basic for Applications, commonly known as VBA. Using the Data ribbon, there are also a number of different methods to connect to SQL Server from different options on the ribbon. These will be demonstrated within the example shortly, but these first few statements show the flexibility of Excel and the security dangers that can exist.

When saving the Excel workbook, the credentials used to access SQL Server are stored, allowing you or anyone with the right tool on their computers the potential to refresh their data almost instantly if required. But keep in mind the security implications: if you are using mixed-mode authentication, you could have someone who you don’t want refreshing the data. In this instance, you would remove the data connection details.

By storing the connection details within the workbook, anyone who gains access to the Excel file could run the code or even execute their own code by editing what was stored, as I just mentioned. If you have Windows authentication, then you may have already locked down the tables so that the user trying to access your SQL Server can’t. This is standard developer practice. With SQL Server/mixed-mode authentication, security becomes more open, and anyone in the world could end up with your Excel sheet and potentially access your server and database. If you must use authentication that is not Windows authentication, then you must lock down your database objects tightly and, if possible, remove the connection details from the Excel sheet and get them provided either by a prompt or some other external method. I realize that this is the third or fourth time I have mentioned this point in very quick succession, but it can be the largest hole in your security if you don’t get it right.

It is now time to look at using Excel to connect to your database and work with your data. The exercise is split into two parts, with the first part of the example using the Data ribbon and the second part using Excel VBA.

Using Excel with the Data Ribbon

The first example will use the Data ribbon. This is a ribbon that exists within Excel for connecting to external data sources, and in the example you will be connecting to the ApressFinancial database. It’s time to dive into the next “Try It Out” exercise.

TRY IT OUT: CONNECTING VIA EXCEL 2010

Using Excel with the steps demonstrated in the previous exercise is in my opinion the simplest method to retrieve data for your users. However, it is possible to take this a stage further so that Excel retrieves the data programmatically and you have the ability to work with the information before placing it in Excel, and this is where VBA can be used.

Using Excel with VBA

In the following exercise, you will see how to build Excel VBA code in a module within a workbook. By having the code in a module rather than a specific sheet, code is available from all sheets, and this is what you will tend to find most often. You will also find that VBA code is quite often initiated from an action, whether it is the Excel sheet opening, a value in a cell changing, or a button placed on a sheet and being pressed. Within the following example, you will step through the code initially within VBA to insert a customer, and then you will place a button on the sheet and call the routine to insert a second customer.

TRY IT OUT: CONNECTING VIA EXCEL VBA

These are two of the most common methods of working with data in Excel. You will find many jobs that look for Excel VBA, and some of these will look for SQL Server access. My experience is that this is a good set of skills to have under your belt, and using Excel via the Developer ribbon is a quick method as a developer to get data out to your users that they can then pivot.

image Caution Always keep in mind that, although there is a link between the VBA code and Excel sheet, the VB Editor is a different IDE to Excel and therefore all code needs to be saved in the VB Editor. Saving the Excel sheet will not save your VBA code.

Excel is a good tool, and you have seen how simple it is to work with SQL Server. All other development tools are just as straightforward to connect to SQL Server. The next tool you will look at is Visual Studio using VB.NET and C#.

Visual Studio

Although you can use Notepad or a third-party tool, the best way to develop a .NET solution is by using Visual Studio or Visual Studio Express. Visual Studio full version (Professional and upward) comes with extra functionality over the Express edition, as you would expect, but the Express edition is more than ample to get you started. Before working with the examples, you can either download the relevant Express edition language of choice or follow the examples, or if you have the full paid edition, you can set up the environment to replicate the development language you will use most.

You can follow and work the examples using any edition. However, if you have the full edition, then when you install you will be asked which language you wish to set Visual Studio to. I have the full edition, and this is what is demonstrated within the examples; my language of choice is C#. This means that when Visual Studio starts, the templates shown by default will be for Visual C#, as shown in Figure 16-26.

images

Figure 16-26. Template Explorer if you have chosen the Visual C# setup at install time

image Note At the time of writing the book, Visual Studio 2010 Professional was used.

If you have the Express edition, then things are a bit simpler. The number of templates is fewer, and the number of default project types that can be built is fewer. Figure 16-27 shows the page that will be displayed when using Visual C# and you are creating a new project (as you will see within the examples).

images

Figure 16-27. Visual C# Express new project template options

Before I take you through some code, there is some terminology to go through first.

Terminology

This section has some of the basic terminology and what it means for .NET. This isn’t a full list, and in fact it is quite limited, but these are terms that are good to know for the following examples.

  • Class: A construct that allows you to create an object or reference methods that are logically linked
  • Module: An object similar to a class but more restricted than a class; it holds the code that can be executed to achieve a goal.
  • .NET libraries: A combination of one or more classes that are built as an executable that can be used to extend functionality of another executable
  • Imports (VB.NET)/using (C#): Statements commonly known as a namespace; they are directives used in VB.NET or C# programs, respectively, to import a .NET reference library to be used in that class. It works as a “code shortcut” so that you don’t have to qualify it each time you want to use something from it.

image Note As readers may read just the section on the technology they want to use, you may see some information repeated in each section.

VB.NET

The first language within Visual Studio that you will explore is VB.NET. In this example, you will build a console application that will execute a stored procedure with a parameter as input. A console application is one that runs and outputs information in a command prompt.

TRY IT OUT: RUNNING A PARAMETERIZED STORED PROCEDURE USING VB.NET

You may still be a little daunted by the foregoing code, but I hope that is not the case. The main points to take away are how to connect to SQL Server and to execute a stored procedure and return a value. If you have found this interesting, then take a look at C#, which is next.

C#

Working with C# has similarities with working with VB.NET, in that you are using Visual Studio, and the logic for achieving the results is the same. It is purely the syntax that differs, at least in the case of our example. Don’t be fooled, though, into thinking that for more complex development this statement is true for all code, as it is not. There are differences between the two languages when you are developing more intricate code, but I have avoided this by keeping the examples simple.

Many VB.NET developers are those that have come from VBA or Visual Basic 6, but with C#, developers will have many different backgrounds such as Java, C++, and Delphi, as well as any of the foregoing.

In the following example, you will use Visual Studio to build a C# console application that will run a parameterized stored procedure called CustomerDetails.apf_CustBalance.

TRY IT OUT: RUNNING A PARAMETERIZED QUERY USING C#

So that’s Visual Studio with VB.NET and C# examples completed. Visual Studio and the .NET languages are the best tools and environments to work with SQL Server as you might expect, as they are Microsoft technologies. However, you can use non-Microsoft technologies, and in the next section you will see how another extremely popular development language can be used via Java.

Java

Java was one of the languages used as a base when Microsoft came to develop C# and is used quite widely for server-side development within firms, especially financial firms. However, Java is more commonly connected to Oracle and Sybase rather than SQL Server in my experience, but the combination of Java to SQL Server does exist. Part of the reason was that connecting to SQL Server from Java had no specific driver and had to use a general ODBC driver. This led to several issues, and therefore the take-up was low.

Connecting to a SQL Server database can be achieved through a Java ODBC connection, which over time has been improved, or you can connect through the Microsoft driver known as SQLJDBC. With Microsoft SQL Server 2012, version 4 of the SQLJDBC driver has been released. This will need to be downloaded from Microsoft and extracted for this section of the chapter. If you are connecting via Windows authentication, as demonstrated in the example, you will also require an authorization library. This will also be part of the demonstration in the following example.

image Tip I will have on my web site links to the locations to download the latest software.

Java and C# have a number of similarities, such as the use of the semicolon as an end-of-line delimiter, the use of namespaces known as packages in Java, the syntax, and statement structures, allowing the learning curve between C# and Java to be less than if you switched to other languages. However, one difference between these two languages surrounds accessing and retrieving data. Sadly all data retrieved is returned as a record set, and therefore you have to read around the record set even to retrieve a scalar value.

Like .NET you can use an integrated development environment to build your solutions, or you can use Notepad and a command-line prompt to compile and run your code. There are several IDEs around, such as NetBeans, but in this book I will use Eclipse.

The following example will connect to the ApressFinancial database, call a new stored procedure called CustomerDetails.apf_CustClearedBalance, which accepts the customer ID as an input parameter, and return the cleared balance as a scalar value. To run this example, you need to have done the following:

  • Downloaded and installed a Java runtime
  • Downloaded and extracted Eclipse
  • Downloaded and extracted the SQLJDBC driver

TRY IT OUT: RETURNING A SCALAR VALUE USING JAVA WITH ECLIPSE

As you will have noticed, there is a great deal of similarity between Java with Eclipse and either VB.NET or C# with Visual Studio. There are differences, of course, but there are a lot of similarities, and therefore if you know one technology, picking up the other from a “server side” of development is not difficult.

image Note Client-side development differs greatly between Java and .NET, and I believe .NET is by far the superior tool to use.

Summary

So you are now at the end of the book and should be feeling confident in working with SQL Server from installation through developing for it. This chapter saw the final piece of the jigsaw, where you could now connect and execute code against a SQL Server database from one of several different languages and tools.

Excel is an excellent basic reporting tool and ideal for retrieving results quickly and efficiently in a well-formatted manner to your users. If you combine this with VBA code, you can perform a huge range of actions, and there are companies that purely use Excel with VBA as their interaction with a database. It’s not perfect in some respects, but users love Excel, and as a developer you can get a front end built and ready in minutes.

However, many of you will turn to .NET and Visual Studio. This is my tool of choice for developing solutions against SQL Server and is the tool that is tuned most efficiently to work with the data. .NET is a powerful complex framework that provides you as a developer with an almost unending set of tools to perform high-performance, low-latency, multithreaded tasks from server to client side, and it is a route that I recommend you explore if you want to become more than a pure SQL Server developer.

Finally you were introduced to Java. For me Java is a very mature language and is found everywhere. Knowing Java is a good basis to move into mobile computing—for example, game development or one of a thousand different avenues. However, it is not so well tuned for SQL Server, which is why you more often find Java used with Oracle or Sybase. However, Microsoft is putting time and effort into this language as it can run on more than Windows, such as Linux, and being able to connect to SQL Server via the Linux operating system opens up a whole new world.

Taking all of these languages and working through examples of each should give you a flavor of what is possible and how you can move forward. Remember that every “Try It Out” exercise is available for download for each development language.

Good luck with SQL Server—it is a wonderful database gaining in strength and functionality all the time, and as a SQL Server developer, using the skills learned in this book as a good grounding, you will be able to build database solutions that can reach around the globe.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.136.168