Welcome! Relax and enjoy yourself as you read this. May I have your full attention please?
Did you read Part 1 of this series? If not, find it at /2010/01/14/3-deadly-career-mistakes-programmers-make-and-how-to-avoid-them-part-1/.
Introduction
Ever wonder why some programmers always seem to get better? They get the jobs they like. They become experts. They develop on fun, rewarding projects. They make good money. They fit the definition of success. Let’s call this the Happy Zone.
Yet other programmers always seem to make little progress. For some reason the right opportunities are never there. They feel frustrated about the projects they develop on. Perhaps they’re not happy about the money they’re making. Let’s call this the Unhappy Zone.
So, why does this happen? Why do these vast disparities exist? Are you in either one of those categories right now? I’ve been in both of them during the course of my programming career and the Happy Zone is MUCH, MUCH better!
In this series of articles, we’re taking an interesting look at 3 of the common career mistakes programmers make that keep them in the Unhappy Zone. By looking at these and evaluating your own situation, you will be one step closer to the Happy Zone. Perhaps if you are already in the Happy Zone, my hopes are that you can get to the Super Happy Zone:)
In the last article (part 1) we talked a bit about motivation and why that’s important to your programming career. I also gave you a simple exercise to get you thinking about your goals (what you want) and why you want them (the rewards of achieving your goals). Did you do the practice exercise yet? Try it. It just takes a few seconds and it will get you thinking. I promised to give you some mental strategies to generate tons of motivation. So here’s a couple of them that you can try too.
Programming Career Motivation Power Strategy 1
The first strategy that I personally live by is: Seek Projects and Opportunities That Are Personally Fun and Gratifying. Avoid projects or assignments that are boring or without personal satisfaction. Think about this for a second. Have you ever taken a job or agreed to work on a project that you knew you probably wouldn’t like? Perhaps the technology wasn’t something you wanted to learn? Or it wasn’t the type of application that you wanted to develop on?
The reason that it’s really important to seek programming projects that are fun for YOU is because you need motivation in order to achieve your goals. If you work on a programming project that you don’t like, you will find it hard to get motivated because of the negative emotions caused by the project. It’s just natural for people to work hard on things that they like and avoid things that they don’t like (it’s just how our brains are wired). Think about it. Do you normally spend your day doing lots of things that you like to do or lots of things that you don’t like to do?
There are many ways that you can practically apply this strategy:
Programming Career Motivation Power Strategy 2
The second strategy is to: Challenge Yourself With Your Own Difficult Extra-Curriculur Programming Projects. Give yourself a challenge outside of work or school. Think of a programming technique or technology that you always wanted to learn and then create a project that gets you some experience working with the technique. Make the project difficult. Preferably you should make it something that is a little above your experience level. This is so that you can grow as a programmer.
Challenges are good! Challenges are necessary! You need challenges to grow and thrive as a programmer. The desire to complete a difficult challenge is a powerful emotion!
Conclusion and What’s Next
Do you have a desire to improve any part of your programming career? Then try some of this tips that I’ve given you! Remember, you are the best person to motivate yourself.
Stay tuned for part 3 where I’m going to reveal the Second Career Mistake Programmers Make and How To Avoid It.
In the meantime, do you seek projects that are fun? Do you challenge yourself outside of your work or school environment? What are the things that you wanted to learn but never did? Quickly leave a comment. I’d love to hear from you!
]]>Welcome! Relax and enjoy yourself as you read this. May I have your full attention please?
Ever wonder why some programmers always seem to get better? They get the jobs they like. They become experts. They develop on fun, rewarding projects. They make good money. They fit the definition of success. Let’s call this the Happy Zone.
Yet other programmers always seem to make little progress. For some reason the right opportunities are never there. They feel frustrated about the projects they develop on. Perhaps they’re not happy about the money they’re making. Let’s call this the Unhappy Zone.
So, why does this happen? Why do these vast disparities exist? Are you in either one of those categories right now? I’ve been in both of them during the course of my programming career and the Happy Zone is MUCH, MUCH better!
In this series of articles, we’re going to take an interesting look at 3 of the common career mistakes programmers make that keep them in the Unhappy Zone. By looking at these and evaluating your own situation, you will be one step closer to the Happy Zone. Perhaps if you are already in the Happy Zone, my hopes are that you can get to the Super Happy Zone:)
This article is devoted to the first common career mistake programmers make: They Do Not Motivate Themselves!
Motivation is so important in programming because you have to spend many hours learning, coding, testing, etc. Let’s face it; if you plan to get good at programming and have a rewarding career, you need motivation.
Let’s chat about motivation in three parts:
1) What motivation actually is.
2) Why motivation is important and why you must do it yourself.
3) How to motivate yourself!
What’s Motivation?
So what is motivation? If you look-up the word “motivate” you will see synonyms like “induce”, “move” and “cause”. You can think of motivation as a force that causes you to take action.
Do you have a desire to improve any part of your programming career? Then you probably already have some motivation. Depending on what it is that you want to improve, you may have a little motivation, or a lot.
Why is motivation important?
Motivation is critical to your success because it’s what induces you to take action and achieve your goals. There are many potential rewards that could motivate you to work towards your goals:
The more motivated you are, the more goals you will achieve.
Less Motivation = Less Chance of Achieving Goals
More Motivation = Higher Chance of Achieving Goals
Why do you have to motivate yourself?
Because if you sit around waiting for someone to inspire you or tell you what you need to do in order to live your programming dreams, what do you think will happen? That’s right. Probably nothing.
Successful programmers are able to motivate themselves! They don’t need anybody to tell them what needs to be done. This is VERY important to understand. Others may inspire you and you may even have mentors, but ultimately the best person to motivate yourself is you. Your future is controlled by you.
How can you motivate yourself?
The key to generating motivation in your programming career is by MANIPULATING YOUR EMOTIONS! That’s right. Sound kinda weird? I know. It’s actually pretty simple and you don’t need to have a degree in psychology either (although if you do it doesn’t hurt).
The way this works is like this: if you aim for goals that give you the rewards you want, you will conjure up positive emotions. The more powerful and positive your emotions are, the more motivation you will have. Strong emotions are great motivators. There are practical mental strategies and exercises that you can use to tweak your emotions in a positive way.
Here’s an easy question and answer technique that’s a great first step motivational exercise. Ask yourself these two questions:
What is it that you want? Think of a goal that you desire in your programming career. Let’s pretend for demonstration purposes that your goal is to “become an ASP.NET programming consultant and work on a large Internet web application”.
Why do you want it? Asking yourself “why” helps you identify your reasons for making the goal become a reality. Here are some example reasons for demonstration that someone might want to be a programmer on a large Internet application:
Did you notice something that all of these example reasons have in common with each other? They all contain words that invoke positive emotions: “rewarding”, “sense of achievement”, “exciting”, “new opportunities” and “so much fun”.
Repeat this simple motivational exercise on your own. You can use it anytime you are creating new goals. Remember to include positive and compelling emotions in your reasons when you answer “why do you want it?”. This will give your brain more energy to focus on fulfilling your goals. You can start the process of generating motivation this way and you can create a positive image in your mind of your future.
Stay tuned for part 2 where I’m going to give you some secret mental strategies to generate tons of motivation and hopefully keep inspiring you.
In the meantime, what motivates you? What are the things that you want in your programming career? Have you ever made the mistake of not motivating yourself? Quickly leave a comment. I’d love to hear from you!
]]>Did you ever wonder what really happens when you type a URL into your web browser and press enter? Or when you enter your credit card information to buy a product and click Complete Order?
In this introductory overview of ASP.NET I’m going to discuss about what exactly ASP.NET really is and how it works to run dynamic web applications. The purpose of this article is to give you a foundation level look at the ASP.NET web application platform and help you understand the basic core concepts of the ASP.NET runtime so that your learning can progress quickly and easily.
So what exactly is ASP.NET and what is the ASP.NET runtime?
In order to answer these two questions we have to cover some basic dynamic website concepts first.
Introduction to web servers and how your browser talks to them
On the World Wide Web, the tool that people use to navigate around and read or watch material is the Web Browser (e.g. Internet Explorer, Firefox, etc.). Web browsers understand a special tag language which is HTML. When you want to visit a website and view the material on that website, you type in the URL (unique address of the website) in your browser window and your browser visits the website.
Once you have typed in the URL and pressed Enter, your web browser starts communicating with the website across the Internet network behind the scenes. The only thing you see is maybe an hourglass or a spinning globe that indicates that something is happening. As you see that globe spinning, your web browser communicates with a special software program behind the scenes called a web server. The web server is a special software application program that is running on the Internet computer that you requested in your URL.
So if you requested a URL that looks like http://bogusinternetserver.com/mypage.html you should know that there is a remote computer on the Internet at the address bogusinternetserver.com and that remote computer is running a special program called a web server. The web server is the program that is responsible for fetching the HTML file that you requested. The web server’s job is to go fetch mypage.html or whatever you typed into your browser.
Static versus Dynamic web pages
Under normal circumstances, the web server will simply fetch the file (mypage.html) that you requested and send it to your browser. Then your browser will display the file in a viewable/readable format (with text, graphics and hyperlinks).
There are other situations however when the file being requested is not a Static file like mypage.html, but instead is a Dynamically created file (mywebpage.aspx). The web server knows that the file is dynamic based on the file extension which in this example is .aspx. When a dynamic file is requested, the web server will pass execution control over to a separate program. That separate program is the ASP.NET runtime, which is responsible for executing the C# code associated with the dynamic web page (mywebpage.aspx) and then sending the results of that web page execution back to the browser.
Comparing when HTML is created statically versus dynamically
Static web files simply contain HTML markup tags and are actual files stored on a hard drive. In contrast Dynamic web files are not really files in the traditional sense. Dynamic web files (ending in .aspx) are a combination of C# code and special ASP.NET server tags that when combined together, can be executed dynamically as the application is running to produce HTML on the fly.
The reason that programmers need dynamic web files on the Internet is so that we can write web enabled applications that do useful things for users like view their bank accounts or buy products using their credit cards. In fact, nowadays the web is filled with dynamic web applications. Every time you type a search into Google or your favorite web search, you are running a dynamic web file. These types of dynamic actions are not possible with traditional HTML tags. Dynamic web files are necessary to process input data that is entered into web page forms. Think about when you fill out your credit card information into a web form and press a Complete Order button. Once that button is clicked, there a dynamic web file that executes to actually process your order.
So what exactly is the ASP.NET runtime again?
The ASP.NET runtime is the special program that dynamically executes ASP.NET web page code and produces HTML that is sent back to the browser. Remember that a web browser only understands HTML, so the end result of a dynamic web page execution must always be HTML. One of the real powers of the ASP.NET platform is that as a programmer you can concentrate on implementing your business requirements and let the ASP.NET runtime worry about creating all the HTML dynamically at execution time.
Take a look at this graphic which depicts the steps that occur whenever a user requests a dynamic web file in their web browser and the request goes to the ASP.NET runtime. Click to enlarge.
Step 1 - The user requests a web page. For example: http://bogusinternetserver.com/mywebpage.aspx
Step 2 - The web page request goes to the web server program.
Step 3 - The web server notices that the file being requested has an extension of .aspx so it transfers execution control to the ASP.NET runtime.
Step 4 - The ASP.NET runtime dynamically executes the code associated with the page mywebpage.aspx. At this point in time, a dynamic web application is running. During the execution of the dynamic web application, many things can occur. The application can communicate with a database. It can process a credit card order. It can perform a search. It can do whatever dynamic operation the programmer who coded the web page had designed the application to do. After the execution is finished, the ASP.NET runtime produces the output which is an HTML formatted document.
Step 5 - The HTML document is delivered to the browser and the user sees the results as a formatted web page with hyperlinks, text, images and all the other things you typically find when you view a web page on the Internet.
So now that we know what the ASP.NET runtime is, then what exactly is ASP.NET?
ASP.NET is a broad high level term that consists of:
-A software server program (the ASP.NET runtime) that interacts with the web server to execute dynamic web pages.
-Development tools (Visual Web Developer and Visual Studio).
-Programming languages (C# and VB.NET).
-The .NET framework libraries.
All of these items together make up the Microsoft ASP.NET web platform, commonly known as “ASP.NET”.
This lesson builds on the knowledge of a some prior lessons. Here are the links to those lessons:
How to use ADO.NET with parameters in ASP.NET to Query a SQL Server database
How to use ADO.NET with parameters in ASP.NET to UPDATE a record in a SQL Server database
How to use ADO.NET with parameters in ASP.NET to INSERT a record into a SQL Server database
In those lessons I covered how to use the ADO.NET SqlCommand and SqlParameter classes (along with the SqlDataAdapter) to run SQL Queries, Updates and Inserts with parameters against an SQL Server database table. If you haven’t read those lessons yet, it is important to do so because they are the foundation for this lesson and I don’t repeat the same material. The code for this lesson also builds on the code from the prior lessons.
In this lesson, I am going to cover how to use the ADO.NET SqlCommand and SqlParameter classes to execute an SQL Delete query with parameters against an SQL Server database table. This lesson applies to ASP.NET with C#.
Why would you need to execute an SQL Delete operation and use parameters?
The answer is whenever you need to remove a record from the database. You need a way to execute the SQL Delete with a “where” clause so that you can make sure to remove a specific record that you are interested in. Normally a Delete where clause will need a unique identifier for the record to be removed. The where clause value for the unique identifier is passed using a parameter.
Let me get started. First the business requirements. In the prior lessons I had created a couple of web forms named GridView_SQLServer.aspx and Customer_Edit.aspx. Those forms display records from a SQL Server database table named “Customer” and allow the user to modify the records.
I have a new requirement which states I must also allow the removal of data in the table Customer. I have to give the user the ability to Delete a record. In order to do that I am going to create a new Delete button on the form Customer_Edit.aspx. This new button will be responsible for giving the user the ability to Delete a customer record in the database.
Let me show you the code for that button so you can see how an ADO.NET SQL Delete is performed with C# and then I will discuss each block of code separately.
string sCustomerId = Request.QueryString["customerid"]; int customerid = int.Parse(sCustomerId); SqlCommand dbcmd = new SqlCommand(); SqlParameter dbparam = null; using (SqlConnection dbconn = new SqlConnection( "Server=localhost;" + "Database=csharpuniversity;" + "User ID=sa;" + "Password=Sqlserverpass$123;" + "Trusted_Connection=False;")) { string SQLDelete = "delete from [customer] " + "where customer_id = @customer_id"; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.Int32; dbparam.ParameterName = "customer_id"; dbparam.Value = customerid; dbcmd.Parameters.Add(dbparam); dbcmd.CommandText = SQLDelete; dbcmd.Connection = dbconn; dbconn.Open(); dbcmd.ExecuteNonQuery(); }
If you read through the prior lessons about ADO.NET SQL Updates and Inserts, you will notice that the code is very similar to this set of code that performs and SQL Delete. In fact, it is almost identical. Now let’s go through each block of code in more detail.
First I get the unique identifier for the record that I need to delete in the database. The database table Customer that I’m trying to delete data from, has a customer_id column that contains an Identity value (a SQL Server automatically incremented number). The customer_id is the unique identifier of a Customer record. I can get this value from the QueryString since it is being passed to the page. Here is how I get the value.
string sCustomerId = Request.QueryString["customerid"]; int customerid = int.Parse(sCustomerId);
After that, inside the using { } block, I start setting up my Delete operation.
string SQLDelete = "delete from [customer] " + "where customer_id = @customer_id";
Notice that I created a string variable named SQLDelete that contains the SQL text for the Delete operation. You can see above that I use a parameter for the customer_id column. Remember from the prior lessons that in an SQL operation, you can use the @ symbol to specify a parameter like @customer_id. That allows ADO.NET to dynamically substitute a value for the variable @customer_id at runtime.
For Oracle, you can use the : (colon) symbol to specify an ADO.NET parameter. So if you were using Oracle as your database, you would change @customer_id to :customer_id.
Then I need to create an SqlParameter object to pass the value of customer_id dynamically.
dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.Int32; dbparam.ParameterName = "customer_id"; dbparam.Value = customerid; dbcmd.Parameters.Add(dbparam);
When you are creating SqlParameter objects, you need to specify the data type, the name of the database column you want to delete data for and the new value for the column. Then you have to add the SqlParameter to the Parameters collection in the SqlCommand object that you are using.
Next to finish off the code for the Delete button, there are four lines of code left.
dbcmd.CommandText = SQLDelete; dbcmd.Connection = dbconn; dbconn.Open(); dbcmd.ExecuteNonQuery();
In those final lines of code I assign the text string for the Delete to the SqlCommand object dbcmd and associate the SqlConnection object with the dbcmd. Then notice that I explicitly open the connection. If you remember from the prior lessons, when I was using the SqlDataAdapter class, I didn’t need to open the connection because the SqlDataAdapter does that automatically. When you are not using the SqlDataAdapter like in this lesson, you have to explicitly open the connection because the SqlCommand object doesn’t do that automatically. The last line of code is a call to the ExecuteNonQuery() method of the SqlCommand class.
ExecuteNonQuery() is used whenever you want to run a database operation and you are not expecting back any data. Examples of when you can use ExecuteNonQuery are when you need to execute SQL Update, Insert or Delete operations.
That wasn’t so hard was it?
You can think of the entire development process of using parameterized ADO.NET Delete operation as follows:
1) Specify your SQL Delete statement with a where clause and use the @ symbol where SqlParameter variables are needed. If you are using Oracle, us the : (colon) symbol to prefix the SqlParameter variable name.
2) Create each SqlParameter object and assign it a name, a type and a value. You can create multiple SqlParameter objects if you need more than one variable in the Delete operation.
3) Associate the SqlConnection object with the SqlCommand object.
4) Open the SqlConnection object.
5) Run the ExecuteNonQuery() method of the SqlCommand object.
This lesson builds on the knowledge of a some prior lessons. Here are the links to those lessons:
How to use ADO.NET with parameters in ASP.NET to Query a SQL Server database
How to use ADO.NET with parameters in ASP.NET to UPDATE a record in a SQL Server database
In those lessons I covered how to use the ADO.NET SqlCommand and SqlParameter classes (along with the SqlDataAdapter) to run SQL query and update operations with parameters against an SQL Server database table. If you haven’t read those lessons yet, it is important to do so because they are the foundation for this lesson. The code for this lesson also builds on the code from the prior lessons.
In this lesson, I am going to cover how to use the ADO.NET SqlCommand and SqlParameter classes to execute an SQL Insert query with parameters against an SQL Server database table. This lesson applies to ASP.NET with C#.
Why would you need to execute an SQL Insert operation and use parameters?
The answer is whenever you need to create a new record in the database. You need a way to pass some data values for the table columns. The data values are passed using parameters.
Let me get started. First the business requirements. In the prior lessons I had created a couple of web forms named GridView_SQLServer.aspx and Customer_Edit.aspx. Those forms display records from a SQL Server database table named “Customer” and allow the user to modify the records.
I have a new requirement which states I must also allow the creation of new data in the table Customer. In order to do that I am going to create a new web form named Customer_Insert.aspx. This new web page will be responsible for giving the user the ability to enter data for a brand new record in the database.
I will put three TextBox controls on the form for the database fields First Name, Last Name and E-mail Address. I will also put a Save Button control that will create the new record in the database when clicked. Let me show you the code for that button so you can see how an ADO.NET SQL Insert is performed with C# and then I will discuss each block of code separately.
string first_name = txtFirstName.Text; string last_name = txtLastName.Text; string email = txtEmail.Text; SqlCommand dbcmd = new SqlCommand(); SqlParameter dbparam = null; using (SqlConnection dbconn = new SqlConnection( "Server=localhost;" + "Database=csharpuniversity;" + "User ID=sa;" + "Password=Sqlserverpass$123;" + "Trusted_Connection=False;")) { string SQLInsert = "insert into [customer] " +" (first_name, last_name, email_address) VALUES ("; SQLInsert += "@first_name "; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.String; dbparam.ParameterName = "first_name"; dbparam.Value = first_name; dbcmd.Parameters.Add(dbparam); SQLInsert += ",@last_name "; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.String; dbparam.ParameterName = "last_name"; dbparam.Value = last_name; dbcmd.Parameters.Add(dbparam); SQLInsert += ",@email )"; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.String; dbparam.ParameterName = "email"; dbparam.Value = email; dbcmd.Parameters.Add(dbparam); dbcmd.CommandText = SQLInsert; dbcmd.Connection = dbconn; dbconn.Open(); dbcmd.ExecuteNonQuery(); }
If you read through the prior lesson about ADO.NET SQL Updates, you will notice that the code is very similar to this set of code that performs and SQL Insert. In fact, it is almost identical. Now let’s go through each block of code in more detail.
First I get the data entered by the user into the TextBox controls on the web form.
string first_name = txtFirstName.Text; string last_name = txtLastName.Text; string email = txtEmail.Text;
After that, inside the using { } block, I start setting up my Insert operation.
string SQLInsert = "insert into [customer] " +" (first_name, last_name, email_address) VALUES ("; SQLInsert += "@first_name "; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.String; dbparam.ParameterName = "first_name"; dbparam.Value = first_name; dbcmd.Parameters.Add(dbparam);
Notice that I created a string variable named SQLInsert that will be progressively built over several lines of code. I have three pieces of information that I need to save to the database: the customer’s first name, last name and e-mail address. That means that I need three SqlParameter objects. You can see above that I create the first SqlParameter for the first_name column. Remember from the prior lessons that in an SQL operation, you can use the @ symbol to specify a parameter like @first_name. That allows ADO.NET to dynamically substitute a value for the variable @first_name at runtime.
For Oracle, you can use the : (colon) symbol to specify an ADO.NET parameter. So if you were using Oracle as your database, you would change @first_name to :first_name.
When you are creating SqlParameter objects, you need to specify the data type, the name of the database column you want to create data for and the new value for the column. Then you have to add the SqlParameter to the Parameters collection in the SqlCommand object that you are using.
I have to also create the SqlParameter objects for the other database columns last_name and email_address.
SQLInsert += ",@last_name "; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.String; dbparam.ParameterName = "last_name"; dbparam.Value = last_name; dbcmd.Parameters.Add(dbparam); SQLInsert += ",@email )"; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.String; dbparam.ParameterName = "email"; dbparam.Value = email; dbcmd.Parameters.Add(dbparam);
So that makes a total of three SqlParameter objects that I created.
Next to finish off the code for the Save button, there are four lines of code left.
dbcmd.CommandText = SQLInsert; dbcmd.Connection = dbconn; dbconn.Open(); dbcmd.ExecuteNonQuery();
In those final lines of code I assign the text string for the Insert to the SqlCommand object dbcmd and associate the SqlConnection object with the dbcmd. Then notice that I explicitly open the connection. If you remember from the prior lessons, when I was using the SqlDataAdapter class, I didn’t need to open the connection because the SqlDataAdapter does that automatically. When you are not using the SqlDataAdapter like in this lesson, you have to explicitly open the connection because the SqlCommand object doesn’t do that automatically. The last line of code is a call to the ExecuteNonQuery() method of the SqlCommand class.
ExecuteNonQuery() is used whenever you want to run a database operation and you are not expecting back any data. Examples of when you can use ExecuteNonQuery are when you need to execute SQL Update, Insert or Delete operations.
That wasn’t so hard was it?
You can think of the entire development process of using parameterized ADO.NET Insert operation as follows:
1) Specify your SQL Insert statement and use the @ symbol where SqlParameter variables are needed. If you are using Oracle, us the : (colon) symbol to prefix the SqlParameter variable name.
2) Create each SqlParameter object and assign it a name, a type and a value. You can create multiple SqlParameter objects if you need more than one variable in the Insert operation.
3) Associate the SqlConnection object with the SqlCommand object.
4) Open the SqlConnection object.
5) Run the ExecuteNonQuery() method of the SqlCommand object.
Take a look at this video that shows me Inserting an SQL Server database record with ADO.NET in ASP.NET.
Stay tuned for the next lesson where I’m going to show you how to Delete a database record using ADO.NET with parameters in ASP.NET.
]]>This lesson builds on the knowledge of a prior lesson entitled “How to use ADO.NET with parameters in ASP.NET to Query a SQL Server database“. In that lesson I covered how to use the ADO.NET SqlCommand and SqlParameter classes (along with the SqlDataAdapter) to run an SQL query with parameters against an SQL Server database table. If you haven’t read that lesson yet, it is important to do so because it is the foundation for this lesson. The code for this lesson also builds on the code from the prior lesson.
In this lesson, I am going to cover how to use the ADO.NET SqlCommand and SqlParameter classes to execute an SQL Update query with parameters against an SQL Server database table. This lesson applies to ASP.NET with C#.
Why would you need to execute an SQL Update operation and use parameters?
The answer is whenever you need to modify or update a record in the database. You need a way to pass some data values for the table columns. The data values are passed using parameters. You also need a way to execute the SQL Update with a “where” clause so that you can specify exactly which database record you are interested in modifying. The where clause values are passed using parameters.
Let me get started. First the business requirements. In the prior lesson I had created a web form named Customer_Edit.aspx. That form displays a specific record in a SQL Server database table named “Customer”.
I had a requirement which states I must allow Editing (or Updating) of the records in the Customer table. In the web form Customer_Edit.aspx I had added some TextBox controls to hold the data from the Customer table. I also added a Save button that will give the user the ability to update the information back to the database table.
In this lesson I’m going to show you how to program the Save button Click event. In order to do that, let’s do a quick review from the prior lesson. Here is what Customer_Edit.aspx does in sequence:
1) GridView_SQLServer.aspx displays a list of records from the Customer table.
2) The user clicks on a hyperlink for a specific record. The GridView_SQLServer.aspx page opens the Customer_Edit.aspx page and passed it some data using a QueryString variable:
Customer_Edit.aspx?customerid=55
3) The Customer_Edit.aspx page opens and the Page_Load event executes. In the Page_Load method, the data for a specific customer is retrieved from the database and the TextBox controls on the page are populated with their corresponding data values.
Now I have to create code for a new step #4:
4) The user modifies the data in the TextBox controls and clicks Save. The information is updated back to the database.
Let me show you what the code looks like for the Save button click event and then I will explain it in more detail.
string first_name = txtFirstName.Text; string last_name = txtLastName.Text; string email = txtEmail.Text; string sCustomerId = Request.QueryString["customerid"]; int customerid = int.Parse(sCustomerId); SqlCommand dbcmd = new SqlCommand(); SqlParameter dbparam = null; using (SqlConnection dbconn = new SqlConnection( "Server=localhost;" + "Database=csharpuniversity;" + "User ID=sa;" + "Password=Sqlserverpass$123;" + "Trusted_Connection=False;")) { string SQLUpdate = "update [customer] set "; SQLUpdate += "first_name = @first_name "; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.String; dbparam.ParameterName = "first_name"; dbparam.Value = first_name; dbcmd.Parameters.Add(dbparam); SQLUpdate += ",last_name = @last_name "; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.String; dbparam.ParameterName = "last_name"; dbparam.Value = last_name; dbcmd.Parameters.Add(dbparam); SQLUpdate += ",email_address = @email "; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.String; dbparam.ParameterName = "email"; dbparam.Value = email; dbcmd.Parameters.Add(dbparam); SQLUpdate += " where customer_id = @customer_id"; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.Int32; dbparam.ParameterName = "customer_id"; dbparam.Value = customerid; dbcmd.Parameters.Add(dbparam); dbcmd.CommandText = SQLUpdate; dbcmd.Connection = dbconn; dbconn.Open(); dbcmd.ExecuteNonQuery(); }
So let’s walk through each of the blocks of code together. First I get the data entered by the user into the TextBox controls on the web form.
string first_name = txtFirstName.Text; string last_name = txtLastName.Text; string email = txtEmail.Text;
Then I get the unique identifier for the record that I need to update in the database. The database table Customer that I’m trying to update, has a customer_id column that contains an Identity value (a SQL Server automatically incremented number). The customer_id is the unique identifier of a Customer record. I can get this value from the QueryString since it is being passed to the page. Here is how I get the value.
string sCustomerId = Request.QueryString["customerid"]; int customerid = int.Parse(sCustomerId);
After that, inside the using { } block, I start setting up my Update operation.
string SQLUpdate = "update [customer] set "; SQLUpdate += "first_name = @first_name "; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.String; dbparam.ParameterName = "first_name"; dbparam.Value = first_name; dbcmd.Parameters.Add(dbparam);
Notice that I created a string variable named SQLUpdate that will be progressively built over several lines of code. I have three pieces of information that I need to save to the database: the customer’s first name, last name and e-mail address. That means that I need three SqlParameter objects. You can see above that I create the first SqlParameter for the first_name column. Remember from the prior lesson that in an SQL operation, you can use the @ symbol to specify a parameter like @first_name. That allows ADO.NET to dynamically substitute a value for the variable @first_name at runtime.
For Oracle, you can use the : (colon) symbol to specify an ADO.NET parameter. So if you were using Oracle as your database, you would change @first_name to :first_name.
When you are creating SqlParameter objects, you need to specify the data type, the name of the database column you want to update and the new value for the column. Then you have to add the SqlParameter to the Parameters collection in the SqlCommand object that you are using.
I have to also create the SqlParameter objects for the other database columns last_name and email_address.
SQLUpdate += ",last_name = @last_name "; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.String; dbparam.ParameterName = "last_name"; dbparam.Value = last_name; dbcmd.Parameters.Add(dbparam); SQLUpdate += ",email_address = @email "; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.String; dbparam.ParameterName = "email"; dbparam.Value = email; dbcmd.Parameters.Add(dbparam);
So that makes a total of three SqlParameter objects that I created. But there is one more parameter that I need. That parameter is for the customer_id column. The customer_id is used in the “where” clause to ensure that only the correct record is updated in the database.
SQLUpdate += " where customer_id = @customer_id"; dbparam = dbcmd.CreateParameter(); dbparam.DbType = System.Data.DbType.Int32; dbparam.ParameterName = "customer_id"; dbparam.Value = customerid; dbcmd.Parameters.Add(dbparam);
Next to finish off the code for the Save button, there are four lines of code left.
dbcmd.CommandText = SQLUpdate; dbcmd.Connection = dbconn; dbconn.Open(); dbcmd.ExecuteNonQuery();
In those final lines of code I assign the text string for the Update to the SqlCommand object dbcmd and associate the SqlConnection object with the dbcmd. Then notice that I explicitly open the connection. If you remember in the prior lesson, when I was using the SqlDataAdapter class, I didn’t need to open the connection because the SqlDataAdapter does that automatically. When you are not using the SqlDataAdapter like in this lesson, you have to explicitly open the connection because the SqlCommand object doesn’t do that automatically. The last line of code is a call to the ExecuteNonQuery() method of the SqlCommand class.
ExecuteNonQuery() is used whenever you want to run a database operation and you are not expecting back any data. Examples of when you can use ExecuteNonQuery are when you need to execute SQL Update, Insert or Delete operations.
That wasn’t so hard was it?
You can think of the entire development process of using parameterized ADO.NET Update operation as follows:
1) Specify your SQL Update statement and use the @ symbol where SqlParameter variables are needed. If you are using Oracle, us the : (colon) symbol to prefix the SqlParameter variable name.
2) Create each SqlParameter object and assign it a name, a type and a value. You can create multiple SqlParameter objects if you need more than one variable in the Update operation.
3) Associate the SqlConnection object with the SqlCommand object.
4) Open the SqlConnection object.
5) Run the ExecuteNonQuery() method of the SqlCommand object.
Stay tuned for the next lesson where I’m going to show you how to Insert a database record using ADO.NET with parameters in ASP.NET.
]]>This lesson builds on the knowledge of a prior lesson entitled “Using the ASP.NET GridView control to query a SQL Server database with ADO.NET”
In that lesson I covered the basics of ADO.NET programming with ASP.NET and C#. Concepts such as the System.Data.SqlClient namespace, the SqlConnection class, the SqlDataAdapter class, and the DataSet class were covered. If you haven’t read that lesson yet, it is important to do so because it is the foundation for this lesson and I don’t repeat the same material.
In this lesson, I am going to cover how to use the ADO.NET SqlCommand and SqlParameter classes (along with the SqlDataAdapter) to run an SQL query with parameters against an SQL Server database table. This lesson applies to ASP.NET with C#.
Why would you need to use parameters with an SQL query?
Whenever you need to find an individual database record or perform a search to retrieve a group of records. In both cases, you need a way to execute an SQL query with a “where” clause so that you can limit the data returned to specific records that you are interested in finding. The where clause values are passed using parameters. This lesson assumes you are searching for a specific record, but you can apply the same technique to search for multiple records.
Let me get started. First the business requirements. In the prior lesson “Using the ASP.NET GridView control to query a SQL Server database with ADO.NET” I had created a web form named GridView_SQLServer.aspx. That form contains an ASP.NET GridView that displays the records in a SQL Server database table named “Customer”.
Let’s say that I have a new requirement which states I must allow Editing (or Updating) of the records in the Customer table. One way I can achieve this is by creating an Edit page that will retrieve the data for a specific Customer record and allow modification of the fields.
I will create a new web form named Customer_Edit.aspx. Then I will add some TextBox controls to hold the data from the Customer table and allow the user to modify the data. I will also add a Save button that will give the user the ability to update the information back to the database table. Here is what my Customer_Edit.aspx looks like inside the form tag:
<asp:Label ID="Label4" runat="server" Text="Edit Customer Record"></asp:Label> <br /> <br /> <asp:Label ID="Label1" runat="server" Text="First Name:"> </asp:Label> <asp:TextBox ID="txtFirstName" runat="server" MaxLength="50"> </asp:TextBox> <br /> <asp:Label ID="Label2" runat="server" Text="Last Name:"> </asp:Label> <asp:TextBox ID="txtLastName" runat="server" MaxLength="50"> </asp:TextBox> <br /> <asp:Label ID="Label3" runat="server" Text="E-mail address:"> </asp:Label> <asp:TextBox ID="txtEmail" runat="server" MaxLength="50"> </asp:TextBox> <br /> <asp:Button ID="btnSave" runat="server" Text="Save" />
Now I need a way to retrieve the individual Customer record when this web form opens. If you want to execute code when a web form opens, you place the code in the special event named Page_Load.
In order to retrieve a specific Customer record from the database, I need to use the unique identifier for a Customer which is the “customer_id” column in my Customer table. In my application, the GridView_SQLServer.aspx page contains a hyperlink to this form Customer_Edit.aspx and it passes a variable named “customerid” by using a QueryString. That variable’s value is dynamically taken from the “customer_id” database column. In the browser this looks something like this:
Customer_Edit.aspx?customerid=55
Notice the QueryString variable follows the ? question mark in the URL. I need to get the value of that variable so I place the following code in my Customer_Edit.aspx Page_Load method:
string sCustomerId = Request.QueryString["customerid"]; int customerid = int.Parse(sCustomerId);
The next step is to write code to execute a query against the database and retrieve the Customer record that I need based on the customerid variable value. To do that I will need to use two ADO.NET database classes that were not in the prior lesson. The first one is the SqlCommand class which allows me to use parameters for queries and the second one is the SqlParameter class which is used to hold the value of the variables used as parameters. These two additional classes are used in conjunction with the SqlDataAdapter and DataSet.
First let me show you what the entire block of code looks like to perform a database search with ADO.NET parameters and then I will talk about each specific section separately:
SqlDataAdapter dbadapter = null; SqlCommand dbcmd = new SqlCommand(); SqlParameter dbparam = null; DataSet dbdata = new DataSet(); using (SqlConnection dbconn = new SqlConnection( "Server=localhost;" + "Database=csharpuniversity;" + "User ID=sa;" + "Password=Sqlserverpass$123;" + "Trusted_Connection=False;")) { dbcmd.CommandText = "select * from customer " + "where customer_id = @customer_id"; dbparam = dbcmd.CreateParameter(); dbparam.ParameterName = "customer_id"; dbparam.DbType = DbType.Int32; dbparam.Value = customerid; dbcmd.Parameters.Add(dbparam); dbcmd.Connection = dbconn; dbadapter = new SqlDataAdapter(dbcmd); dbadapter.Fill(dbdata); }
Now, I will go into each individual section and talk about what is going on with this code. The declaration section contains a declaration for the four variables needed in this example:
SqlDataAdapter dbadapter = null; SqlCommand dbcmd = new SqlCommand(); SqlParameter dbparam = null; DataSet dbdata = new DataSet();
Notice that I had to instantiate the SqlCommand object. This is necessary in order to be able to create an SqlParameter object further down in the code. I also had to instantiate the DataSet object which is always necessary before you try to put data into it.
Next, I created the SqlConnection object inside the “using” keyword and passed the connection string for the database. I’m not going to go over that again since it was covered in the prior lesson.
Then, I set the value of the CommandText property for the SqlCommand object:
dbcmd.CommandText = "select * from customer " + "where customer_id = @customer_id";
That is where I am able to specify the SQL query to use for the search operation. Notice that I placed a variable named @customer_id inside the query literal text. The @ symbol is used for Sql Server parameters in Select, Update, Insert and Delete operations. Think of the @ variable as a placeholder that will get dynamically replaced with a value at runtime. For Oracle, you can use the : (colon) symbol to specify an ADO.NET parameter. So if you were using Oracle as your database, you would change @customer_id to :customer_id. Not a big difference is it?
Now I need a way to specify the value of the @customer_id variable for my search query. in order to do that I have to create an SqlParameter object:
dbparam = dbcmd.CreateParameter(); dbparam.ParameterName = "customer_id"; dbparam.DbType = DbType.Int32; dbparam.Value = customerid; dbcmd.Parameters.Add(dbparam);
Notice that I had to create the SqlParameter object by using a method in the SqlCommand class named CreateParameter(). I also had to specify the name of the parameter which must match exactly with what I put in my query text (customer_id). I need to specify the type of the variable which is in Integer and assign a value to the parameter. Notice that I assigned the value of the variable customerid which came from the QueryString. I also need to add the parameter to the SqlCommand Parameters collection by using the Add() method.
After setting up the SqlParameter object, all I have to do is assign an SqlConnection object to the SqlCommand and then pass the SqlCommand to the SqlDataAdapter object which executes the query by using the Fill() method.
dbcmd.Connection = dbconn; dbadapter = new SqlDataAdapter(dbcmd); dbadapter.Fill(dbdata);
Not so bad is it? You can think of the entire development process of using parameterized ADO.NET queries as follows:
1) Specify your SQL Select query statement and use the @ symbol where SqlParameter variables are needed. If you are using Oracle, us the : (colon) symbol to prefix the SqlParameter variable name.
2) Create the SqlParameter object and assign it a name, a type and a value. You can create multiple SqlParameter objects if you need more than one variable in the “where” clause.
3) Associate the SqlConnection object with the SqlCommand object and then pass the SqlCommand object to the SqlDataAdapter constructor.
One final thing that I am going to do is to take the data from the DataSet object and populate the TextBox controls on the web form with the associated data values from the database.
if (dbdata.Tables[0].Rows.Count > 0) { txtFirstName.Text = dbdata.Tables[0].Rows[0]["first_name"].ToString(); txtLastName.Text = dbdata.Tables[0].Rows[0]["last_name"].ToString(); txtEmail.Text = dbdata.Tables[0].Rows[0]["email_address"].ToString(); }
Notice that I’m checking to see if any data was found that matches my query by using an “if” statement and checking the Rows collection of the DataTable object that is inside the DataSet. To retrieve the data value for each TextBox control, I also have to reference the Rows collection. Since there should be only one row returned because this is an exact match search based on a unique identifier column, I check the row number zero 0: Rows[0]. In order to reference a specific column in a DataSet object with only a single row you can use the following convention:
dbdata.Tables[0].Rows[0][”NAME OF COLUMN”]
And replace NAME OF COLUMN with your database table’s column name. You also should replace the name of the DataSet variable dbdata and replace with your variable name.
Take a look at this video that shows me executing dynamic ADO.NET queries using parameters.
Stay tuned for the next lesson where I’m going to show you how to give the user the ability to Update the data back to the database.
]]>I want to take a quick second and thank YOU for subscribing and for all your comments! You really do help me make csharpuniversity.com the best website for amazing asp.net. Over the next few weeks I will be posting lots of new articles and making additional improvements to the website so I look forward to hearing from you as you continue to learn more and enjoy reading what I have to say.
]]>It appears that Microsoft is stressing flexibility in the new CSharp C# 4.0. Microsoft has made an attempt to address some of the C# language’s constraints by offering additional ways of doing things for certain types of coding scenarios in C# 4.0.
Named and Optional parameters for Methods
In C# 3.5 and before you have to pass all of the parameters that a method is expecting in order to be able to compile the application. Take a look at this method declaration:
public DataSet SearchDatabaseTable(string first_name, string last_name) { //perform database search and return DataSet object }
In order to call that method I would have to pass two string values:
//call the method by passing both expected parameters DataSet mydata = SearchDatabaseTable("Martha", "Livingston");
This is all fine, but when you want to create methods that are more flexible and more generic you may have to create additional versions of the same method. For example, let’s say I wanted to have the same method SearchDatabaseTable but I wanted the flexibility to be able to search by first name by itself, last name by itself or both first name and last name together. With this scenario I would have to create three different versions of essentially the same method, but with different parameters declared (three different method signatures):
public DataSet SearchDatabaseTable(string first_name, string last_name) public DataSet SearchDatabaseTableByFirstName(string first_name) public DataSet SearchDatabaseTableByLastName(string last_name)
That seems like extra work just to get this requirement implemented doesn’t it? Well, there is another option that I have been using for years that solves this problem or at least creates an acceptable workaround. The way I have been handling this is by creating only one generic method like SearchDatabaseTable and then passing parameters with certain predefined values to indicate that a parameter should be ignored by the method. For example, I may pass “” (the empty string) for a string argument to indicate that the Method should ignore that parameter. Or I may pass -1 for an Integer parameter to indicate that the Method should ignore that parameter.
This workaround seems to be okay and it works fine, however it suffers from some shortcomings. First the caller must still pass all of the method arguments, regardless of whether or not all of the parameters are being used. Another problem is that the caller of the method must know what the values of the parameters are which indicate that a particular parameters should be ignored. For example the caller of my method would need to know to pass -1 to have an Integer parameter ignored. While these are certainly not showstopper problems it would be nice to have an easier and better way to handle the requirement. In fact, when working with database searches, you may find yourself needing flexibility in order to support a variety of search options; I know I certainly would like some more flexibility without the extra coding.
C# 4.0 has added two new features to address this kind of problem. Those features are: Named parameters for methods and Optional parameters for methods.
In order to make a method parameter Optional, in C# 4.0 you provide a default value for the parameter in the method declaration:
public DataSet SearchDatabaseTable(string first_name = "", string last_name = "")
Notice in this example that I provided default empty string “” values for both of the method parameters. I can then call the method in any of the following ways:
//Passing both values DataSet mydata = SearchDatabaseTable("Martha", "Livingston"); //OR Passing no values, the method will use the defaults DataSet mydata = SearchDatabaseTable(); //OR Passing only the value for first name, //the method will use the default value for last name DataSet mydata = SearchDatabaseTable("Martha");
The other new option with methods is to call them using Named parameters. To call a method using Named parameters you have to prefix a parameter value with the parameter name and a colon : character. Take a look at the following alternative ways to call the SearchDatabaseTable method:
//Passing both values by name DataSet mydata = SearchDatabaseTable(first_name: "Martha", last_name: "Livingston"); //OR Passing both values by name but in a different order DataSet mydata = SearchDatabaseTable(last_name: "Livingston", first_name: "Martha"); //OR Passing only the last name parameter //the method will use the default value for first name DataSet mydata = SearchDatabaseTable(last_name: "Livingston"); //OR Passing only the first name parameter //the method will use the default value for last name DataSet mydata = SearchDatabaseTable(first_name: "Martha");
You can see that by using Named parameters, you have a lot more flexibility when calling a method. I think that is great personally.
Stay tuned for the next article where I will cover more of the new features in C# 4.0. Until then, what are you looking forward to in C# 4.0?
]]>One of the most notable enhancements in .NET 4.0 is the new version of CSharp C# 4.0. According to Microsoft, C# 4.0 will emphasize dynamic programming. You will be able to dynamically instantiate and interact with objects which adds flexibility and code simplification in certain circumstances. You will be able to pass parameters to methods by name instead of having to pass by position. You will be able to declare default parameter values for methods. You will be able to program with generics in an easier fashion and with more flexibility. That can especially prove useful when using LINQ for database programming since generics are involved with LINQ. There are also some COM Interop enhancement features in C# for dealing with COM interfaces like the Microsoft Office Automation APIs.
Another cool new enhancement that will ship with .NET 4.0 is Velocity. Velocity is an enhanced and scalable caching framework for applications and it offers:
Velocity is going to be really useful for web applications that have a high volume of users and are hosted in web farms.
Here are some additional new improvements in the .NET Framework 4.0:
Stay tuned for my next set of articles where I will be discussing the improvements in CSharp C# 4.0 and Visual Studio 2010. What would you like to see in the new .NET Framework 4.0?
]]>