asp.net: Is sqlConnection ADO? - asp.net

Is sqlConnection ADO, if not, what's the name of the layer?
To invoke ADO, (to access non-MS db's), is OleDbConnection the prefered choice?

SqlConnection is part of the ".NET Data Provider for SQL Server", so it is ADO.NET, not to be confused with the old COM-based ADO.
Also, yes I believe OleDBConnection is preferred for Access. I do not believe there is an out-of-the box native data provider for MS Access.

1) The SqlConnection Class is part of the System.Data.SqlClient namespace, and is considered part of ADO.NET.
2) OleDbConnection is for connecting to OLE databases. If you're talking about building a platform-agnostic data access layer, you should use System.Data.Common.DbProviderFactories to create generic DbConnection, DbCommand, etc, objects as in the following code example:
Dim objFactory As DbProviderFactory = DbProviderFactories.GetFactory(ConfigurationManager.AppSettings("DbType"))
Dim objConnection As DbConnection = objFactory.CreateConnection
objConnection.ConnectionString = strConnectionString
In this example, you'd keep the name of the actual provider you're using in your Application Settings.
Note that the generic DB objects only support lowest-common-denominator methods so if you're looking for something platform-specific, you're out of luck. Also of course you will have to specify a valid DBtype to the provider factory, which means you'll have to use either one of the built in providers (ODBC, MS SQL, Oracle, OLEDB) or a third party one. I think you could get away with ODBC if you have a ODBC driver for your platform, but I don't know much about that one.
For information on the different connection objects included in ADO.NET: MSDN-Connecting to Data Sources

Yes it is part of ADO.NET. If you use SqlConnection, actually it is a part of ADO.NET to make a connection between your application and database.

Related

How to access SQL Server from my WCF web service?

VS Express 2012, SQL Server Express 2012, Win 8.1
Hello,
I have a (very) simple WCF hosted as a web service on IIS. I also have a SQL Server instance (with 1 table) installed on the same machine.
I need a step-by-step guide on how to connect to SQL from the WCF (VB) and retrieve a single record from the table (ie: "SELECT LAST NAME FROM MYTABLE WHERE PK = 1;"). That's it. I don't need a 1,200 page manual -- which is all Google keeps throwing at me.
Anyone know of a quick, clean resource?
Thanks,
Jason
The main classes that are involved are SqlConnection and SqlCommand. The documentation of the classes contains some samples on how to use them. To get you started, here is a small sample:
Dim connStr = "Data Source=SQLServerName\InstanceName;Initial Catalog=DatabaseName;Integrated Security=SSPI"
Using conn As New SqlConnection(connStr)
conn.Open()
Using cmd = conn.CreateCommand()
cmd.CommandText = "SELECT LAST_NAME FROM MYTABLE WHERE PK = #pk"
cmd.Parameters.AddWithValue("#pk", 1)
Dim result = cmd.ExecuteScalar()
If Typeof result Is DbNull Then
' Handle null value
Else
' Otherwise
End If
End Using
End Using
This sample assumes that you want to retrieve a single cell as in your statement. If you want to retrieve tabular data, have a look a the SqlDataReader or SqlDataAdapter class.
Please note that - especially in server applications - it is important to dispose of the created instances properly.
There is no difference on using ADO.NET in a WCF service or in a normal application from the point of view of the classes required.
The first thing needed is a connection string that allows your SqlConnection object to find the host and the database that you want to use. Here examples on connection strings
Then you usually need a SqlCommand that encapsulates the SQL text and parameters needed to retrieve the data (Here you setup your SELECT statement and conditions)
Finally you need a SqlDataReader that get the result of the command execution and allows you to loop over the results.
Here a sample that could get you started.
Keep in mind that this is just a minimal todo-list and there are numerous other ways to work with data. Basic objects like SqlDataAdapter, Dataset, DataTable present different ways to load data from a database and use that data. Then on top of these there are technologies like Linq To Sql and Object Relational Mapper tools that abstract the data access and offer high level functionality on top of data.
That's probably the reason you get so much informations on data access technologies

Connect to SQL server using Linq, asp.net

I`m creating a website using asp.net, and I need to use a local SQL server (using Microsoft SQL server). And I have created database and tables in it using the MS SQL Server Management Studio.
Now I successfully connect to the database and do some simple add/query using the following commands:
string connectionString = "data source=ABCD\\SQLEXPRESS;initial catalog=PMD;Trusted_Connection=yes;";
string sqlQuery = "INSERT INTO PMD (username, userID, userAddress)";
sqlQuery += " VALUES (#user, id, add)";
SqlConnection dataConnection = new SqlConnection(connectionString);
SqlCommand dataCommand = new SqlCommand(sqlQuery, dataConnection);
dataCommand.Parameters.AddWithValue("user", USER.Value);
dataCommand.Parameters.AddWithValue("id", ID.Value);
dataCommand.Parameters.AddWithValue("add", ADDRESS.Text);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
The command above can add one column to the table, with values stated.
The query is done in a similar way. Compared with Linq, this is not very concise.
So I was wondering how can I change the code so I can use Linq.
The biggest question for me now is how to connect to the base. I already know all the syntax of Linq.
eg: var query=from c in db.username where c.Contain(“Micheal”) select c (or maybe db.PMD.username)
How can I get the db to link with ABCD/SQLEXPRESS, table PMD?
First you need an Object/Relational Mapper (O/RM). You can't just put LINQ on top of your old ADO.NET code.
Microsoft provides two: Linq2SQL and Entity Framework.
Linq2SQL has been discontinued. If I had to choose between the two, I'd go with Entity Framework.
Here you can find an introduction: http://www.asp.net/entity-framework
For example, install Entity Framework, then connect to sql server with entity framework

Constructing the Connection String for the DataContext Class

I see a couple of DataContext connection string questions. I'm going to try to differentiate this one a bit:
How does one construct a generic connection string to a database, localhost | User-PC\User | Some database... (it is hosted/managed by Microsoft SQL 2008)
I notice that it is IDisposable. So if I have multiple users hitting my site, my code can only access the database one instance at a time, and has to wait until each instance is disposed, in order for the data to be consistent for each user?
Is it possible, by any chance, to somehow enable LINQ in F#-Interactive, and connect to the database from there? I cannot figure out how to enable/load the System.Data dll into fsi. Maybe that is unique to my installation, or it is a common thread? (ie, my installation also does not recognize windows.base.dll--I have to manually get it from programs\reference assemblies).
Anyhow, I've pretty much conclusively discovered that
let x = new System.Data.Linq.DataContext("localhost")
...does not work.
1) How does one construct a generic connection string to a database?
There is no generic way to construct a connection string. The best thing to do is to keep the connection string in some configuration file where you can change it depending on your configuration (the name of SQL Server machine, authentication options, whether it is a file-based database or normal). There is a web site with examples for most of the options.
2) I notice that it is IDisposable. So if I have multiple users hitting my site, my code can only access the database one instance at a time [...]?
No, this is not how DataContext works. The DataContext does not keep a live connection to the server that would block anybody else from using the SQL server. It keeps some state (i.e. cached entities that were already obtained) and it uses optimistic concurrency to make sure that the state is consistent (you can use transactions to prevent other connections, if that's what you want).
3) Is it possible, by any chance, to somehow enable LINQ in F#-Interactive [...]?
That shouldn't be a problem. You can reference assemblies using #r "foo.dll" in F# interactive. The typical approach for F# 2.0 is to generate the data context using C# tools and then just reference it (for F# 3.0, things are easier because you can just use type provider).
If you generate LINQ to SQL data context for Northwind in C#, the F# Interactive use would look like this:
#r #"<whatever_path>\Northwind.dll"
#r "System.Data.Linq.dll"
open Northwind
open Microsoft.FSharp.Linq
let connStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=<path>\NORTHWND.MDF;" +
#"Integrated Security=True;User Instance=True"
let operation () =
// Using 'use' to make sure it gets disposed at the end
use db = new NorthwindDataContext(connStr)
// do something with the database
There actually is a somewhat generic way to construct a connection string:
open System.Data.Common
open System.Data.SqlClient
let providerName = "System.Data.SqlClient"
let factory = DbProviderFactories.GetFactory(providerName)
let cnBuilder = factory.CreateConnectionStringBuilder() :?> SqlConnectionStringBuilder
cnBuilder.DataSource <- "localhost"
cnBuilder.InitialCatalog <- "MyDatabase"
cnBuilder.IntegratedSecurity <- true
let connStr = cnBuilder.ConnectionString
My approach was to have 1 connection string and then use that for all of my DataContext connections. So this code builds the EntityConnectionString based on MyConnString:
protected override MyEntities CreateObjectContext()
{
string ConnString =ConfigurationManager.ConnectionStrings["MyConnString"];
string seConn = ConfigurationManager.ConnectionStrings["MyEntities"].ToString();
EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder(seConn);
ecsb.ProviderConnectionString = ConnString;
EntityConnection ec = new EntityConnection(ecsb.ToString());
ScheduleEntities ctx = new ScheduleEntities(ec);
return ctx;
}

Using same connection string in a DataContext constructor and SqlConnection

I am preparing to deploy a web service that uses SqlConnection primarily as its means to get to the database, and I am adding some new methods that use a DataContext instead of that, and the default constructor and DBML file would use a connection string refering to my development machine (I believe...)
The connection string that the SqlConnection objects use is hard coded into a separate class (don't ask). If I provide the DataContext with the same connection string as the SqlConnections will that work instead of modifying the DBML or Web.config?
The connection string that is used in these objects is:
Dim cn As New SqlClient.SqlConnection
cd.ConnectString = ApplicationInfo.ConnectString 'Connection string is stored here
So will this work too? Do I have to change something else?
Dim db As New FADataContext(ApplicationInfo.ConnectString)
Where ApplicationInfo.ConnectString is a hard coded string that has the properties of the connection. I don't have physical access to the production SQL server or Web server therefore can't use the DBML designer to edit the connection string. And they aren't stored in the .config files.
I'm pretty sure that would work. I know when you use Entity Framework you can send a connection string in the DataContext and it works fine. Although the connection string has more information in it then regualar connection strings, like the name of the csdl, msl, ssdl or whatever.

Convert Access data base to SQL Server

I've created an application using ASP.NET with Access DB, now I found somee.com who support only SQL Server DBs, so Now I must convert my Access DB to SQL Server DB.
Is there any tool who can do the trick ?
This is some code I'm using in my web application :
Public Shared Function conecter() As OleDbConnection
Dim MyConnexion As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & System.AppDomain.CurrentDomain.BaseDirectory & "/Learning.mdb")
MyConnexion.Open()
Return MyConnexion
End Function
Public Shared Function lecture(ByVal requete As String) As OleDbDataReader
Dim Mycommand As OleDbCommand = conecter().CreateCommand()
Mycommand.CommandText = requete
Dim myReader As OleDbDataReader = Mycommand.ExecuteReader()
Return myReader
End Function
In this case, If I convert my database I must change the OleDbConnexion and other things or I can just leave them like that ?
Your connection string will need to change. Connectionstrings.com is a good resource for this if you're having problems figuring out how to set up a SQL connection string.
For upward migration, take a look at the Access Upsize Wizard - this link is for 2002 since I'm not sure what access version you have.
If for some reason you do not have sufficient access to your SQL database to handle an upsize directly, you'll likely need to just generate the database schema and knock out a bit of migration code.
If you have access 2007, there is inbuilt option convert access database to SQL other wise there are somany tools available for free.
bullzip free converter
Try MUST
It was developed by a colleague of mine (we designed the website: www.upsizing.co.uk).
It does a fair bit more than the MS tools.

Resources