Link to home
Start Free TrialLog in
Avatar of trevor1940
trevor1940

asked on

C#: Getting started with Databases

Databases are an must in most programming so I'm wondering what is the best way to do it in C#?
Can someone suggest a online tutorial I can get started with?
I'm not asking how to build a database nor how to Wright SQL queries

I found a tutorial here  I'm surprised he is writing sql statements  within the flow shouldn't they be separated?
In the very first block of code seems wrong

Shouldn't there be a test to see  if the connection is actually open before using it?

  private void button1_Click(object sender, EventArgs e)
  {
   string connetionString;
   SqlConnection cnn;
   connetionString = @"Data Source=WIN-50GP30FGO75;Initial Catalog=Demodb;User ID=sa;Password=demol23";
   cnn = new SqlConnection(connetionString);
   cnn.Open();
   MessageBox.Show("Connection Open  !");
   cnn.Close();
  }

Open in new window

Further in the tutorial he binds a database column to a text box and DataGridView I didn't get that far unsure if this was the correct  method


Anyway I've used that tutorial and some data from here  to create my first console app bellow
I get the feeling I'm missing something especially not hard coding a query with a doctors name  in the real world this would be from a user input so how dose C# combat SQL injection?

I'm using an SQLite database I'm assuming the general principles are the same

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.IO;

namespace sqlite_test
{
    class Program
    {
        private static SQLiteConnection m_dbConnection;

        static void Main(string[] args)
        {
            if (File.Exists("D:\\Vb\\Test\\sqlite-test\\HelloWorld.sqlite"))
            {
                m_dbConnection = new SQLiteConnection("Data Source=D:\\Vb\\Test\\sqlite-test\\HelloWorld.sqlite;Version=3;");
                m_dbConnection.Open();



                string sql = @"SELECT d.FirstName AS dFirstName, d.LastName AS dLastName, a.DoctorID AS Did, p.PatientID AS PID, p.FirstName, p.LastName, a.aDate, a.aTime 
                            FROM
                            Doctors d, Patients p, Appointments a
                            WHERE
                             a.DoctorID = d.DoctorID AND
                            a.PatientID = p.PatientID AND
                            dFirstName = 'NANCY'";

                SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
                SQLiteDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("Doctor = {0}: {1}: ", reader[0].ToString(), reader[1].ToString());

                }

            }
            else
            {
                Console.WriteLine("Wot no DB?");       
            }
            Console.ReadLine();


        }
    }
}

Open in new window

Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Regarding the SQL Injection, you tend to create a Command, and then add Parameters that contain the data. Something along these lines:

var cmd = new SQLiteCommand("SELECT col1, col2, col3 FROM yourTable WHERE someCol = @SomeValue");
cmd.Parameters.AddWithValue("@SomeValue", "Your Value");

Open in new window

"Databases" is a generic term. You should really qualify what you mean by that. There are relational databases, hierarchical databases, "no-sql" databases, graph databases, etc. Heck, an Excel spreadsheet could be used as a database.

Based on your use of "sql", I assume you're interested in relational databases.
Avatar of Kimputer
Kimputer

- "Shouldn't there be a test to see  if the connection is actually open before using it?" - The program could've force closed on your, correct. Better use DB connect in a Try Catch statement then (as well as all updates/save to database etc.).
- "SQL Injection": you can easily sanitize input, make sure only regular characters are passed on, if you know that field only contains regular characters
- "binds a database column to a text box and DataGridView": Depends on your needs, if you want to display only, or need editing. Putting the DG view back in one go, with only line of code (updates db where necessary), or you want to do the update sql yourself?
Avatar of trevor1940

ASKER

Yes I'm talking about a relational database specifically PostgreSQL / PostGIS, MySQL and SQLite these are the 3 I currently use

I'm assuming from your comments there are multiple ways to utilize a  relational database so can anyone recomend a tutorial?
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
+1 for Entity Framework.


»bp
Thanx for the advise
I'm sure I'll be back with additional EF questions
Not sure if these will be of any help, but here are some links that I had saved when I was getting up to speed on related topics on a C# MVC project a while back.  The links aren't in any particular order, so you might want to browse a bit before digging in, the best "intro" items aren't necessarily the first items in the list.

In addition, for small money you can probably find a decent course or two on Udemy related to EF, if you like online learning versus pure self study.  They seem to offer heavy discounts much of the time so for around $10 you can often find useful content.

Udemy Online Courses - Entity Framework Search

LINQ

Entity Framework

Lambda Expressions


»bp
Thanx BP

From a novice point of view it's often knowing where to start and how to filter the good from the erm not so good.
For instance I was reading article it started of OK but it lost me around creating the tables with the use of it's table names  the SQL I'm OK with

I also find some of the  Microsoft Docs daunting
I agree, that's why you see a number of saved links from me.  I tend to bounce around a bit and take what I feel is useful from each reference.  It's an iterative process too, at least for me.  Sometimes I read something and I learn a bit more, but can't get through the whole thing yet because I haven't digested the first part, and tried do it myself.  Then later I might revisit for reference on more advanced concepts, etc.


»bp
Reading technical docs is an art form in itself and does take some getting used to.

With EF, you have a couple of options when working with database. If you already have a database created, then you follow the database-first methodology. You make a link to your DB and EF then generates the classes based of the scheme that already exists. You interest with these classes in your code.

If you don't already have a database, then you tend to follow the code-first methodology. Basically, you create classes (models) that represent your entities. You use the single name for the classes - Customer, User, Order, Product etc. When you then run your app, EF will create the DB tables for you and the table names will be the pluaralised version of your Model. So a Customer model will automatically generate a Customers table, an Order model will generate an Orders table, etc. You can override that if you need to,

Effectively, a Code-First approach generally means that you never need to even look at the Database. It's all done with code !