Using SqlParameters()

In my last post I showed you my first ASP.NET code that I programmed, a first for many years.  I also talked about why the code isn’t very friendly, and quite basic which could provide hackers with a way to manipulate the SQL.

Well as promised I’ve rewritten the code and included a SqlParameter to thwart any hacking.

Here is the new code from the code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace Diary
    public partial class WebForm1 : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            Datebox.Text = System.DateTime.Now.ToString();

        protected void Button1_Click(object sender, EventArgs e)
            SqlConnection conn;
            SqlParameter DateParam;
            SqlParameter NoteParam;

            conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NoteBook.mdf;Integrated Security=True;User Instance=True");

            SqlCommand MyCommand = new SqlCommand();

            MyCommand.CommandText = "Insert NoteBook (Date, Note) Values (@Datep, @Notep)";
            MyCommand.CommandType = CommandType.Text;
            MyCommand.Connection = conn;

            DateParam = new SqlParameter();
            DateParam.ParameterName = "@DateP";
            DateParam.SqlDbType = SqlDbType.DateTime;
            DateParam.Direction = ParameterDirection.Input;
            DateParam.Value = Convert.ToDateTime(Datebox.Text).ToString("yyyy-MM-dd");

            NoteParam = new SqlParameter();
            NoteParam.ParameterName = "@NoteP";
            NoteParam.SqlDbType = SqlDbType.NVarChar;
            NoteParam.Direction = ParameterDirection.Input;
            NoteParam.Value = Notebox.Text;




The additional of MyCommand , DateParam/NoteParam commands.

The plan is to continue with developing this program in the weeks and months ahead.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: