简体   繁体   中英

SqlConnection in VS2015 C#

I am extremely new to C# web development (or any development for that matter) but I am trying to figure out how to save the results from a SQL query to a variable. I think I understand the process, but many of the examples I am finding on the Web use a SqlConnection statement. My copy of Visual Studio does not seem to have that command (pretty sure I am using the wrong word here). What am I missing either softwarewise or knowledgewise accomplish my task?

Thank you in advance for your help. Dep

It depends on what you want to do: insert, update, get data. It also depends if you want to use an ORM library or not. I all depends. The code that I copy below is an example of how to retrieve a DataTable using Ado.Net (as you mentioned SqlConnection):

You have to use:

using System.Data;
using System.Data.SqlClient;

This is the code for retrieving a DataTable

    private DataSet ExecuteDataset(string query)
    {
        var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
        DataSet ds;
        try
        {
            conn.Open();
            ds = new DataSet();
            var da = new SqlDataAdapter(query, conn);
            da.Fill(ds);
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            conn.Dispose();
            conn.Close();
        }
        return ds;
    }

       private DataSet ExecuteDataset(string query, SqlParameter[] parametros)
        {
            var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
            DataSet ds;
            try
            {
                conn.Open();

                SqlCommand command = conn.CreateCommand();
                command.CommandText = query;

                foreach (SqlParameter p in parametros)
                {
                    command.Parameters.Add(p);
                }

                ds = new DataSet();
                var da = new SqlDataAdapter(command);
                da.Fill(ds);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                conn.Dispose();
                conn.Close();
            }
            return ds;
        }

This is the code for running a query that does not expect result with and without parameters:

    private void ExecuteNonQuery(string query)
    {
        var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
        try
        {
            conn.Open();
            SqlCommand command = conn.CreateCommand();
            command.CommandText = query;
            command.ExecuteNonQuery();
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            conn.Dispose();
            conn.Close();
        }
    }

    private void ExecuteNonQuery(string query, SqlParameter[] parametros)
    {
        var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
        try
        {
            conn.Open();
            SqlCommand command = conn.CreateCommand();
            command.CommandText = query;

            foreach (SqlParameter p in parametros)
            {
                command.Parameters.Add(p);
            }

            command.ExecuteNonQuery();
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            conn.Dispose();
            conn.Close();
        }
    }

Here is the simplest example I can think of, take note of the using statements and comments

using System;
using System.Data;
using System.Data.SqlClient;

namespace DataAccess
{
    class Program
    {
        static void Main(string[] args)
        {
            //Use your database details here.
            var connString = @"Server=localhost\SQL2014;Database=AdventureWorks2012;Trusted_Connection=True;";

            //Enter query here, ExecuteScalar returns first column first row only
            //If you need to return more records use ExecuteReader/ExecuteNonQuery instead
            var query = @"SELECT [AccountNumber]
                          FROM [Purchasing].[Vendor]
                          where Name = @Name";

            string accountNumber = string.Empty;

            //Using statement automatically closes the connection so you don't need to call conn.Close()
            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand(query, conn);
                //Replace @Name as parameter to avoid dependency injection
                cmd.Parameters.Add("@Name", SqlDbType.VarChar);
                cmd.Parameters["@name"].Value = "Michael";
                try
                {
                    conn.Open();
                    //Cast the return value to the string, if it's an integer then use (int)
                    accountNumber = (string)cmd.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            Console.WriteLine(accountNumber);
            //ReadKey just to keep the console from closing
            Console.ReadKey();

        }
    }
}

If you are really new to C# with SQL Server, I would recommend to start from scratch using one of the tutorials shown here . It provides a lot of information in a step-by-step manner:

  1. The basics
  2. Clearly definition of the core ceoncepts
  3. How to setup dependencies to get started
  4. How to choose between development models (code, model vs. database first)
  5. How to write queries

and much more.

Using SqlConnection is a valid choice, but requires more effort in writing the queries for doing basic stuff like selecting, updating, deleting or inserting data. You actually have to construct the queries and take care to build and dispose the commands.

On a related note:

The new way of doing all database-related activities in C# or .NET would be to harness Entity Framework (EF), and try to move away from any ADO.NET-based code. The latter still exists and hasn't been marked as obsolete, though. You may want to use ADO.NET for small apps or for any PoC tasks. But, otherwise, EF is the way to go.

EF is an ORM, and is indeed built as a repository pattern and generates a conceptual layer for us to work with. All of the nuances of the connection and command are completely encapsulated from us. This way, we don't have to meddle with these bare-bones.

If you want to do it well, you have to edit a file named Web.config in your project and put something like this inside (with your own DB data):

<connectionStrings >
    <add
         name="myConnectionString" 
         connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;"
         providerName="System.Data.SqlClient"/>

</connectionStrings>

Then, in the code, you can use it with:

SqlConnection con = new SqlConnection(
    WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);

Finally you can do that you want with "con", for example:

string queryString = "SELECT name, surname FROM employees";

SqlCommand command = new SqlCommand(queryString, con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
    while (reader.Read())
    {
        Console.WriteLine(String.Format("{0}, {1}",
        reader["name"], reader["surname"]));
    }
}
finally
{
    reader.Close();
}

i use this nuget library. https://www.nuget.org/packages/SqlServerDB_dotNET/

using SqlServerDB;

string server = @"INSTANCE\SQLEXPRESS";
string database = "DEMODB";
string username = "sa";
string password = "";

string connectionString = @"Data Source="+ server + ";Initial Catalog="+ database + "; Trusted_Connection=True;User ID="+ username + ";Password="+ password + "";
DBConnection db_conn = new DBConnection(connectionString);

Console.WriteLine("IsConnected: " + db_conn.IsConnected());
if (db_conn == null || !db_conn.IsConnected())
{
Console.WriteLine("Connessione non valida.");
return;
}

string sql = "SELECT ID, Message FROM Logs ORDER BY IDLic;";
DataTable dtLogs = db_conn.SelectTable(sql);

if (dtLogs == null || dtLogs.Rows.Count == 0)
return;

// Loop with the foreach keyword.
foreach (DataRow dr in dtLogs.Rows)
{
Console.WriteLine("Message: " + dr["Message"].ToString().Trim());
}

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