Click here to Skip to main content
15,890,825 members
Articles / Web Development / ASP.NET
Tip/Trick

DBConnect

Rate me:
Please Sign up or sign in to vote.
1.29/5 (11 votes)
9 Jun 2018CPOL1 min read 14.4K   116   6   4
This is a simple C# class for connect and using SQL Server easily (SELECT, INSERT, UPDATE, DELETE)

You can select a query in just three lines of code.

Introduction

It is very necessary to use database in applications for storing and reading data whether you are a beginner or a professional programmer. This class is based on DataTable object to read data from MS SQL database. For running a query, you need just to call a function to do it.

DBConnect can be used in C# applications and ASP.NET websites.

Total Code

C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace EasyTeb
{
    public class DBConnect
    {
        SqlConnection connection;
        SqlCommand cmd;
        SqlDataAdapter adapter;
        bool isset = false;

        public DBConnect()
        {
            connection = new SqlConnection("Server=.\SQLEXPRESS;
                         Database=TalashNet;Integrated Security=True;");
        }

        public string Script(string Query)
        {
            if (isset)
            {
                try
                {
                    cmd = new SqlCommand(CheckInject(Query), connection);
                    object result = cmd.ExecuteScalar();
                    if (result == null)
                        return "1";
                    else
                        return result.ToString();
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
            return "0";
        }

        public DataTable Select(string Query)
        {
            if (isset)
            {
                DataTable dt = new DataTable();
                adapter = new SqlDataAdapter(CheckInject(Query), connection);
                adapter.Fill(dt);
                return dt;
            }
            return new DataTable();
        }

        public void Connect()
        {
            if (!isset)
            {
                connection.Open();
                isset = true;
            }
        }

        public void DisConnect()
        {
            if (isset)
            {
                connection.Close();
                //connection = null;
                adapter = null;
                cmd = null;
                isset = false;
            }
        }

        public string CheckInject(string sql)
        {
            sql = sql.Replace("--", " ");
            sql = sql.Replace("/*", " ");
            //sql = sql.Replace('%', ' ');
            //sql.Replace('*', ' ');
            return sql;
        }

        public string CheckInjectText(string sql)
        {
            sql = sql.Replace(',', ' ');
            sql.Replace('$', ' ');
            sql.Replace('^', ' ');
            sql.Replace('%', ' ');
            return sql;
        }
    }
}

Using the Code

First, create a class file (.cs) and write the above code in it.

Then, go to your form for calling a query from SQL Server.

If you want to SELECT a query from SQL, you must use this code:

C++
string query = "SELECT * FROM [MyTable]";
DBConnect db = new DBConnect();
db.Connect();
DataTable dt = db.Select(query);
db.DisConnect();

Now, we have a DataTable containing the results of your query. You can show it on a DataGridView or use its data in behind code.

Example of show DataTable in a GridView in ASP.NET:

C++
GridView1.DataSource = dt;
GridView1.DataBind();

Example of show DataTable in a DataGridView in C# Windows application:

C++
DataGridView1.DataSource = dt;

You must use this code if you want to DELETE or INSERT or UPDATE query to SQL:

C++
DBConnect db = new DBConnect();
db.Connect();
db.Script(query);
db.DisConnect();

Points of Interest

This class helps programmer to easily use SQL Server. I hope this class will help you to write your programs faster than before.

History

I wrote this simple class in 2008. It is the second version of DBConnect.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Talashnet.com
Iran (Islamic Republic of) Iran (Islamic Republic of)
i'm sina. i was programming about 10 years.(from 2007)
i write C#.Net, ASP.Net, php applications and developing websites by using HTML5, CSS3 and JS.
i invite you to see our website: Talashnet.com

tnx,

Comments and Discussions

 
QuestionBut beside of all of this ... Pin
LightTempler12-Jun-18 7:59
LightTempler12-Jun-18 7:59 
Question[My vote of 2] This invites too much trouble Pin
MadMyche11-Jun-18 4:01
professionalMadMyche11-Jun-18 4:01 
General[My vote of 2] A somewhat confused interface Pin
John Brett10-Jun-18 21:44
John Brett10-Jun-18 21:44 
Whilst I appreciate the intent of this class, I believe that the use of it would cause more problems that it solves.

Observe the following behaviours :-
If the Connect() method has not been called, Script() returns "0"
If Script() receives no data, it returns "1"
If Script() encounters an error, it returns the exception message
If Script() receives a value, then it returns that value, converted into a string.

If I call Script(), how should I interpret the results? How do I figure out whether I forgot to call Connect(), the database returned nothing, it returned 0, it returned 1, the database returned the text "The connection has been closed unexpectedly" &c. It's too ambiguous to be useful.

Similarly, Select() hides the fact that Connect() hasn't been called first by returning an empty table.

If you want a useful wrapper for SqlCommand, you could consider:
Having the class take care of calling Connect() when necessary, relieving the caller of that concern
Allowing exceptions to throw, so that you're not hiding errors


On a separate note, the idea of checking for SQL injection attacks in the arguments isn't viable. Either use static text in the code, where a hacker has no access, or use SQL parameters to your SqlCommand. Anything else you do will be vulnerable to some clever hacker.

John
GeneralRe: [My vote of 2] A somewhat confused interface Pin
Sina Shiri Hamedani11-Jun-18 2:33
professionalSina Shiri Hamedani11-Jun-18 2:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.