简体   繁体   中英

Is my approach to query Database using a class correct?

I am fairly new into the world of programming. I am trying to learn to program by myself, so i would appreciate if somebody could let me know if my approach is correct.

I am trying to create a class(in C#) which can be used to run queries on a MS-SQL Database. As I am just beginning I am using ADO.net. So instead of having so many DB statements in my code I decided to create a Class for querying DB.

I created a Class Dbclass , and created a method in the class for select query - SelectQuery , which returns a Dataset.

To be more clear below is the class that I have created.

public class Dbclass
{
    private SqlConnection DBcon = null;
    private string ConStr = "";

    public Dbclass(string Constring)
    {
        this.ConStr = Constring;
        DBcon = new SqlConnection(this.ConStr);
    }

    public DataSet SelectQuery(string[] coloumns,string[] tables,string cond)
    {
        string col = string.Join(",", coloumns);
        string tbl = string.Join(",", tables);
        string selectSQL = "SELECT " + col + " FROM " + tbl + cond;
        SqlCommand cmd = new SqlCommand(selectSQL, this.DBcon);
        SqlDataAdapter ada = new SqlDataAdapter();
        DataSet retrnds = new DataSet();
        try
        {
             this.DBcon.Open();
             ada.SelectCommand = cmd;
             ada.Fill(retrnds);
        }
        catch (Exception err)
        {
             string error = err.ToString();
        }
        finally
        {
             this.DBcon.Close();
        }
        return retrnds;
    }
}

So my question is, am I doing the right thing as a beginner to create such a class? Is my OOP approach correct?

It would be nice if someone could guide me to a better approach.

In my opinion it is better to use ORM approach. You could use entity just as normal objects inside your program, and it's more secure vs SQL injection attacks.

We use Entity in our project and it's made my life very easy. For example if I would like to retrieve list of rich people:

var minimumSalary = 10000;
var richPeople = database.People.Where(o => o.Salary > minimumSalary).ToList();

There is no correct answer for your question however this is what I use.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;

namespace Core.DataAccess.OleDb
{
    public static class DataInterface
    {
        public static DataTable DoRead(string connectionString, string commandText)
        {
            return DoRead(connectionString, commandText, new OleDbParameter[] { });
        }

        public static DataTable DoRead(string connectionString, string commandText, OleDbParameter[] parameters)
        {
            OleDbConnection connection = new OleDbConnection(connectionString);

            OleDbCommand command = new OleDbCommand(commandText, connection);

            foreach (OleDbParameter p in parameters)
            {
                command.Parameters.Add(p);
            }

            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command);

            DataTable table = new DataTable();
            table.Locale = System.Globalization.CultureInfo.InvariantCulture;
            dataAdapter.Fill(table);
            return table;
        }

        public static void DoWrite(string connectionString, string commandText)
        {
            DoWrite(connectionString, commandText, new OleDbParameter[] { });
        }

        public static void DoWrite(string connectionString, string commandText, OleDbParameter[] parameters)
        {
            OleDbConnection connection;
            OleDbTransaction transaction;

            connection = new OleDbConnection(connectionString);
            connection.Open();

            transaction = connection.BeginTransaction();

            OleDbCommand command = new OleDbCommand(commandText, connection);

            foreach (OleDbParameter p in parameters)
            {
                command.Parameters.Add(p);
            }

            try
            {
                command.Transaction = transaction;
                command.ExecuteNonQuery();
            }
            finally
            {
                transaction.Commit();
                connection.Close();
            }
        }

        public static OleDbParameter CreateOleDbParameter(string name, OleDbType type, object value)
        {
            OleDbParameter parameter = new OleDbParameter();
            parameter.OleDbType = type;
            parameter.ParameterName = name;
            parameter.Value = value;
            return parameter;
        }
    }
}

You pass into each method the connection string, a parameterized SQL query and optional parameters.

var connectionString = "my connection string";
var commandText = "INSERT INTO Person (ID, Name, Age) VALUES (?, ?, ?)";

var parameters = new List<OleDbParameter>();
parameters.Add(new OleDbParameter { Value = "12345" }); // id
parameters.Add(new OleDbParameter { Value = "Joe Bloggs" }); // name
parameters.Add(new OleDbParameter { Value = 35 }); // age

Core.DataAccess.OleDb.DataInterface.DoWrite(connectionString, commandText, parameters.ToArray());

Yes Overall it's okay, here are few things that raise flags:

  public Dbclass(string Constring)
    {
        this.ConStr = Constring;
        DBcon = new SqlConnection(this.ConStr);
    }

Connection Object aren't meant to be reused. Of course it saves you time and code. But really you want to create an new instance of the Connnection and dipose them when you no longer need them.

Also this:

    try
    {
      //.......
    }
    catch (Exception err)
    {
         string error = err.ToString();
    }
    finally
    {
         this.DBcon.Close();
    }

This is ok you know, but it .net 4 you want to take advantage of IDisposable, where you don't have to manually dispose the connection.

public DataSet SelectQuery(string[] coloumns,string[] tables,string cond)
{
    using (SqlConnection DBcon= new SqlConnection(this.ConStr))
    {
        string col = string.Join(",", coloumns);
        string tbl = string.Join(",", tables);
        string selectSQL = "SELECT " + col + " FROM " + tbl + cond;
        SqlCommand cmd = new SqlCommand(selectSQL, this.DBcon);
        SqlDataAdapter ada = new SqlDataAdapter();
        DataSet retrnds = new DataSet();
        try
        {
             this.DBcon.Open();
             ada.SelectCommand = cmd;
             ada.Fill(retrnds);
        }
        catch (Exception err)
        {
             string error = err.ToString();
        }
        //no need for this.DBcon.Close();

        return retrnds;
    }
}       

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