George Blissett
George Blissett

Reputation: 43

Trying to get a SQL entry into C#

I'm trying to get an SQL entry into C# and then set the entry value to a Decimal - Price.

I'm writing the result of my the SQL entry to console and then attempting to read it again, but it will only allow me to read it as an INT.

{
public partial class Purchase : System.Web.UI.Page
{   

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void purchaseButton_Click(object sender, EventArgs e)
    {
        SqlConnection sqlConnection1 = new SqlConnection("Data Source=DELETED);
        SqlCommand cmd = new SqlCommand();
        SqlDataReader reader;

        string url = HttpContext.Current.Request.Url.AbsoluteUri;
        char ID = url[url.Length - 1];
        cmd.CommandText = "SELECT Price FROM customerData where ProductId =" + ID;
        cmd.CommandType = CommandType.Text;
        cmd.Connection = sqlConnection1;

        sqlConnection1.Open();

        reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            ReadSingleRow((IDataRecord)reader);
        }

        int Price = Console.Read();
        PriceTest.Text = Price.ToString();

        reader.Close();




        sqlConnection1.Close();

    }
         private static void ReadSingleRow(IDataRecord record)
    {
        Console.WriteLine(String.Format("{0}, {1}", record[0], record[1]));

    }

I've intentionally removed my data-source from this for obvious reasons.

I have attempted to have code that is alongs the line of:

Decimal Price = Console.Read();

I'm not sure if this method works in retrieving the data from SQL as I have no way of testing it. If anyone could shine some light on how to do this id be very grateful, Also sorry for the bad English it is not my first language. Thank you

Upvotes: 0

Views: 78

Answers (1)

Nir
Nir

Reputation: 29614

You can't read from a database by dumping the data into the console and then reading it back, the console is for user input/output not for copying data inside your code.

To get the value as decimal you need, inside your ReadSingleRow method use decimal price = (Decimal)record[0] if the data is decimal in the db or decimal price = Convert.ToDecimal(record[0]) if it's not.

Also, as @Milney said in a comment, you have an SQL injection vulnerability there, you need to change your SQL to:

cmd.CommandText = "SELECT Price FROM customerData where ProductId = @ID";
cmd.Parameters.AddWithValue("@ID",ID);

Upvotes: 1

Related Questions