简体   繁体   中英

Confused and stuck on a datareader problem SQL Server / .NET

I'm trying to work on a generic webpage for SQL Server metrics, these can be from queries/stored procedures etc. These might be in different databases and tables, and I want them in a nice format.

Say I have a URL that looks like this:

   localhost:0000/Metric/framework?database=db1&table=t1&records=100
OR localhost:0000/Metric/framework?database=db1&table=t2&records=100
OR localhost:0000/Metric/framework?database=db2&table=t9&records=10
  • (DONE) Open Web page - code gets database/table/recordCount from the URL (Dynamic)

  • (DONE) Creates a connection to SQL

  • (DONE) Runs a query or stored procedure

  • (DONE) Casts ALL of the returned field types in to TYPE STRING, so that way I don't have to worry about faffing about matching my model to the SQL Server table.

  • (DONE) Then displays the results for the query/stored procedure

  • (DONE) I don't even have to mess around with the HTML side of things either, that's why I have the NAME as well as the VALUE in my model, that way I make the table heading from the Model.

I'm trying to do it as simple as possible, as it's just a few scripts that I want to be able to query through a web page, that way I can click on a URL and have metrics in front of me in seconds, without having to log in to SQL run a script, change database etc.

The way I have it working is: I just look at the number of fields I want to use, then add those new lines to the model _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 etc, but then the tricky bit comes in with the conversion of Type X to String. And for the 10 fields I would have to have 10 of those sections.

Example Webpage 1

1. int    ID           Casts to String
1. string Description  Casts to String
1. date   "2022-12-01" Casts to String

This would be a _0 _1 _2 field model

Example Webpage 2

1. int      ID            Casts to String 
1. currency Price         Casts to String
1. currency Qty           Casts to String
1. date     "2022-12-01"  Casts to String
1. bool     Yes           Casts to String

This would be a _0 _1 _2 _3 _4 field model

Everything works and I can make a model of the returned fields, and I can change all of the types in to Strings get them in to the Model and display them on a separate page, so it's a win.

But it's not elegant in the slightest.

The tricky part, how can I make it so it has the minimal coding for the conversion?

I thought to iterate through them, but have been unable to do so.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.VisualBasic.FileIO;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;

namespace Metric_Tracker.Pages.Metric
{
    public class FrameworkModel : PageModel
    {
        public List<frameworkInfo> frameworks = new List<frameworkInfo>();
  
        public void OnGet()
        {
            try
            {            
                string database = HttpContext.Request.Query["database"].ToString();

                if (database == null || database == String.Empty)
                {
                    database = "database";
                }

                string table = HttpContext.Request.Query["table"].ToString();

                if (table == null || table == String.Empty)
                {
                    table = "table";
                }
                tablename = table;

                string records = HttpContext.Request.Query["records"].ToString();

                if (records == null || records == String.Empty)
                {
                    records = "10";
                }

                string connectionString = "Data Source=.;Initial Catalog=" + database + ";integrated security=True;TrustServerCertificate=True";

                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    string sql = "SELECT TOP (" + records + ") * FROM " + table ;
                    string fieldtype = "";

                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                frameworkInfo framework = new frameworkInfo();
                                framework.fieldname_0 = (reader.GetName(0).ToString());
                                fieldtype = (reader.GetFieldType(0).ToString());
    
                                // Arrrggggghhhhh

                                if (fieldtype == "System.Int64") { framework.field_0 = (reader.GetInt64(0).ToString()); }
                                else if (fieldtype == "System.Int32") { framework.field_0 = (reader.GetInt32(0).ToString()); }
                                else if (fieldtype == "System.Int16") { framework.field_0 = (reader.GetInt16(0).ToString()); }
                                else if (fieldtype == "System.String") { framework.field_0 = (reader.GetString(0).ToString()); }
                                else if (fieldtype == "System.DateTime") { framework.field_0 = (reader.GetDateTime(0).ToString()); }
                                else if (fieldtype == "System.Char") { framework.field_0 = (reader.GetChar(0).ToString()); }
                                else if (fieldtype == "System.Decimal") { framework.field_0 = (reader.GetDecimal(0).ToString()); }
                                else if (fieldtype == "System.Double") { framework.field_0 = (reader.GetDouble(0).ToString()); }
                                else if (fieldtype == "System.Boolean") { framework.field_0 = (reader.GetString(0).ToString()); }
                                else if (fieldtype == "System.Byte") { framework.field_0 = (reader.GetByte(0).ToString()); }
                                else if (fieldtype == "System.UInt16") { framework.field_0 = (reader.GetInt16(0).ToString()); }

                                framework.fieldname_1 = (reader.GetName(1).ToString());
                                fieldtype = (reader.GetFieldType(1).ToString());
                                if (fieldtype == "System.Int64") { framework.field_1 = (reader.GetInt64(1).ToString()); }
                                else if (fieldtype == "System.Int32") { framework.field_1 = (reader.GetInt32(1).ToString()); }
                                else if (fieldtype == "System.Int16") { framework.field_1 = (reader.GetInt16(1).ToString()); }
                                else if (fieldtype == "System.String") { framework.field_1 = (reader.GetString(1).ToString()); }
                                else if (fieldtype == "System.DateTime") { framework.field_1 = (reader.GetDateTime(1).ToString()); }
                                else if (fieldtype == "System.Char") { framework.field_1 = (reader.GetChar(1).ToString()); }
                                else if (fieldtype == "System.Decimal") { framework.field_1 = (reader.GetDecimal(1).ToString()); }
                                else if (fieldtype == "System.Double") { framework.field_1 = (reader.GetDouble(1).ToString()); }
                                else if (fieldtype == "System.Boolean") { framework.field_1 = (reader.GetString(1).ToString()); }
                                else if (fieldtype == "System.Byte") { framework.field_1 = (reader.GetByte(1).ToString()); }
                                else if (fieldtype == "System.UInt16") { framework.field_1 = (reader.GetInt16(1).ToString()); }

                                ETC... 
                                frameworks.Add(framework);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //some exception
            }
        }
    }

    public class frameworkInfo
    {
        public string? fieldname_0;
        public string? field_0 = "";

        public string? fieldname_1;
        public string? field_1 = "";

        Etc...
    }
}

This is how I'm outputting the table. As you will see I have the fields from my model, this might make it easier to understand what I'm trying to do.

<table class="table">
    <thead>
        <tr>
            foreach (var item in Model.framework)
        {
            <tr>
                <td> item.fieldname_0 </td>
                <td> item.fieldname_1 </td>
                <td> item.fieldname_2 </td>
                <td> item.fieldname_3 </td>
                <td> item.fieldname_4 </td>
            </tr>
            break;
        }
        </tr>
    </thead>

    <tbody>
        foreach (var item in Model.framework)
        {
            <tr>
                <td> item.field_0 </td>
                <td> item.field_1 </td>
                <td> item.field_2 </td>
                <td> item.field_3 </td>
                <td> item.field_4 </td>
            </tr>
        }
    </tbody>
</table>

This part is working for me thank you so much for your assistance. This will save me lots of cutting and pasting: 2 lines of code for each field and almost no overhead in the code, I can now knock out as many of these pages as needed for my project in about 2 minutes.

frameworkInfo framework= new frameworkInfo();

framework.field_0 = Convert.ToString(reader.GetValue(0));
framework.fieldname_0 = (reader.GetName(0).ToString()); 

framework.field_1 = Convert.ToString(reader.GetValue(1));
framework.fieldname_1 = (reader.GetName(1).ToString());

framework.field_2 = Convert.ToString(reader.GetValue(2));
framework.fieldname_2 = (reader.GetName(2).ToString());

framework.field_3 = Convert.ToString(reader.GetValue(3));
framework.fieldname_3 = (reader.GetName(3).ToString());

framework.field_4 = Convert.ToString(reader.GetValue(4));
framework.fieldname_4 = (reader.GetName(4).ToString());

frameworks.Add(framework)

You can simply use Convert.ToString , just check if the value is not null before it:

using (SqlCommand command = new SqlCommand(sql, connection))
{
    using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
           for (int i = 0; i < reader.FieldCount; i++)
                if (reader.GetValue(i) != DBNull.Value){
                   framework.field_1 = Convert.ToString(reader.GetValue(i)));
                 }
         }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM