What is the most straightforward way to retrieve data from a local SQL Server database?

梦想与她 提交于 2019-12-11 16:46:51

问题


I don't need/want any security measures (username/password, etc.) - I just want to create a simple example of retrieving data from the AdventureWorks "lite" database (AdventureWorksLT2012_Data.mdf), storing that data in a generic list.

I have the following code to query an MS Access database. Would it be basically the same except for the connection string and query statement?

public SQLServerPOCRepository()
{
    using (var conn = new OleDbConnection(
        @"Provider=Microsoft.ACE.OLEDB.12.0;User ID=User;Password=Pass;Data Source=C:\SWin\DATA\SDAT42.MDB;Jet OLEDB:System database=C:\SWin\Data\wgeg.mdw"))
    {
        using (var cmd = conn.CreateCommand())
        {
            cmd.CommandText = "SELECT td_duckbill_accounts.dept_no, IIF(ISNULL(t_accounts.name),'No Name provided',t_accounts.name) AS name FROM t_accounts INNER JOIN td_duckbill_accounts ON t_accounts.account_no = td_duckbill_accounts.account_no ORDER BY td_duckbill_accounts.dept_no";
            cmd.CommandType = CommandType.Text;
            conn.Open();
            int i = 1;
            using (OleDbDataReader oleDbD8aReader = cmd.ExecuteReader())
            {
                while (oleDbD8aReader != null && oleDbD8aReader.Read())
                {
                    int duckbillNum = oleDbD8aReader.GetInt16(0);
                    string duckbillName = oleDbD8aReader.GetString(1);
                    Add(new Platypus { Id = i, dbillNum = duckbillNum, Name = duckbillName });
                    i++;
                }
            }
        }
    }
}

The Add() method populates a generic list with an instance of the model Platypus class.


回答1:


You need to update your connection string to use the System.Data.SqlClient provider, along with Integrated Security.

<add name="AdvWorksLT_ConnectionString" 
    connectionString="AttachDBFilename=C:\MyApplication\AdventureWorks.MDF;Integrated Security=True;User Instance=true" 
    providerName="System.Data.SqlClient"/>

Also, you need to use a SqlConnection, SqlCommand and SqlDataReader instead of the OleDbConnection, OleDbCommand, and OleDbDataReader.




回答2:


You just need to set Integrated Security=True :

myConn = New SqlConnection("Initial Catalog=xxx.; Data Source=xxx;  Integrated Security=True")



回答3:


Sure, if you want to continue using OleDbConnection then you can just change the connection string and the query. That being said, it is better to use the ADO Sql Server Native Client. I believe Ole DB support for Sql Server is being deprecated, and 2012 will be the last version to officially support it:

http://technet.microsoft.com/en-us/library/ms130978.aspx




回答4:


The way I prefer to do it is to create an method that accepts an IDataReader, and let that do the DataMapping/Serialization/Hydrating.

That allows the IDataReader to be created outside the code (Jet or Sql Server or Other), and then reused.

I also don't like "0", "1", etc. Here is my typical IDataReader/DataMapper code. (See bigger code block later in this post)

As far as your original question, most DataTypes will match up. However, I remember a few times between Jet and SqlServer, the datatypes were slightly off.

The workaround was use the GetValue(), and the cast it.

Instead of this:

decimal pubPrice = dataReader.GetDecimal(Layout.COLUMN0);

It ended up being like this:

decimal pubPrice = Convert.ToDecimal   (accessDataReader.GetValue (Layout.COLUMN0));

Again, I was testing against an IDataReader being created against an OleDB (Jet/Access) vs Sql Server. I think I was testing with the pubs database, both the Jet(Access) version and the corresponding Sql Server version. Most times it was fine. But once in a while I had to tweak and use the less "specific" "GetValue()" method, over the concrete getter (GetDecimal() for example).

[Serializable]
public partial class Employee
{
    public int EmployeeKey { get; set; }                   
    public string LastName { get; set; }                   
    public string FirstName { get; set; }   
    public DateTime HireDate  { get; set; }  
}

[Serializable]
public class EmployeeCollection : List<Employee>
{
}   

internal static class EmployeeSearchResultsLayouts
{
    public static readonly int EMPLOYEE_KEY = 0;
    public static readonly int LAST_NAME = 1;
    public static readonly int FIRST_NAME = 2;
    public static readonly int HIRE_DATE = 3;
}


    public EmployeeCollection SerializeEmployeeSearchForCollection(IDataReader dataReader)
    {
        Employee item = new Employee();
        EmployeeCollection returnCollection = new EmployeeCollection();
        try
        {

            int fc = dataReader.FieldCount;//just an FYI value

            int counter = 0;//just an fyi of the number of rows

            while (dataReader.Read())
            {

                if (!(dataReader.IsDBNull(EmployeeSearchResultsLayouts.EMPLOYEE_KEY)))
                {
                    item = new Employee() { EmployeeKey = dataReader.GetInt32(EmployeeSearchResultsLayouts.EMPLOYEE_KEY) };

                    if (!(dataReader.IsDBNull(EmployeeSearchResultsLayouts.LAST_NAME)))
                    {
                        item.LastName = dataReader.GetString(EmployeeSearchResultsLayouts.LAST_NAME);
                    }

                    if (!(dataReader.IsDBNull(EmployeeSearchResultsLayouts.FIRST_NAME)))
                    {
                        item.FirstName = dataReader.GetString(EmployeeSearchResultsLayouts.FIRST_NAME);
                    }

                    if (!(dataReader.IsDBNull(EmployeeSearchResultsLayouts.HIRE_DATE)))
                    {
                        item.HireDate = dataReader.GetDateTime(EmployeeSearchResultsLayouts.HIRE_DATE);
                    }


                    returnCollection.Add(item);
                }

                counter++;
            }

            return returnCollection;

        }
        //no catch here... see  http://blogs.msdn.com/brada/archive/2004/12/03/274718.aspx
        finally
        {
            if (!((dataReader == null)))
            {
                try
                {
                    dataReader.Close();
                }
                catch
                {
                }
            }
        }
    }


来源:https://stackoverflow.com/questions/21315210/what-is-the-most-straightforward-way-to-retrieve-data-from-a-local-sql-server-da

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!