How to connect ado.net database to ASP.Net MVC 5 - c#

I'm new to ASP.Net MVC 5 and have previously created two applications using ASP.Net Webforms and Ado.Net Database connections.
I've seen many articles explaining how to use Ado.Net connection in ASP.Net MVC, but all the tutorials are using Entity Framework. Is there any way to connect only Ado.Net?
In my WebForm application I've been using this connection code:
connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "SQL Statement";
cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
}
Is it possible to use this in ASP .Net MVC5?
When I tried I got this error:
Cannot open database "online_recharge" requested by the login. The login failed.
Login failed for user 'IIS APPPOOL\DefaultAppPool'.
This is the code I tried using:
public ActionResult Add_Balance()
{
string record;
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
SqlCommand sqlCmd = new SqlCommand("Select * from COMMISSION_PACKAGE",sqlConnection);
SqlDataReader reader = sqlCmd.ExecuteReader();
record = reader["PKG_NM"].ToString();
sqlConnection.Close();
}
ViewBag.Demo = record;
return View();
}

There's nothing stopping you from using ADO.NET in MVC.Entity Framework is a very popular ORM and it's really simple to set up that's why people like using it for tutorials.But if you need a more custom\controlled way of accessing your data you can still use ADO.NET.
Just a tip - don't store your connection in code, that's considered bad practice.If the database is moved to a different server you will need to change code and re-compile the whole application.You should store the connection string in the *.config file:
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"/>
</connectionStrings>
And can access it from your code like this:
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

Related

How to connect to a local SQL Server database in ASP.NET using Visual Studio 2015?

I built a simple test app with one form when submitting the form the form data should be saved in database
namespace WebApplication3.Controllers
{
public class Home-controller : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Customer customer)
{
// string ATNMEntities = ConfigurationManager.ConnectionStrings["ATNMEntities"].ConnectionString;
using (SqlConnection con = new SqlConnection("data source=A3LABPCLENOVO\\SQLEXPRESS;initial catalog=ATNM;integrated security=True"))
{
string query = "INSERT INTO Customers(Customerid,Name, Country) VALUES(#Customerid,#Name, #Country)";
query += " SELECT SCOPE_IDENTITY()";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#Customerid", customer.Customerid);
cmd.Parameters.AddWithValue("#Name", customer.Name);
cmd.Parameters.AddWithValue("#Country", customer.Country);
// customer.Customerid = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
}
return View(customer);
}
}
}
Connection string:
<connectionStrings>
<add name="ATNMEntities"
connectionString="metadata=res://*/Models.AdoEntityDataModel1.csdl|res://*/Models.AdoEntityDataModel1.ssdl|res://*/Models.AdoEntityDataModel1.msl;provider= System.Data.EntityClient;provider connection string="data source=A3LABPCLENOVO\SQLEXPRESS;initial catalog=ATNM;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
Your posted code:
uses "manual" ADO.Net style of creating a connection, command, and (lacks/commented) execution. So if your "issue" is it's not inserting to the SQLExpress defined in your connection string, then that's where you should look.
While your web.config sample is an Entity Framework (EF) connection that isn't even used in any of your posted code. Probably used elsewhere since it's there...
The link referenced shows how you can define your connection string(s) in web.config instead of writing out as you have in your code, as well as how to put it all together thereafter
Add in Web.config
in Code behind
SqlConnection con = new SqlConnection(ConfigurationManger.Conectionstring["ATNMEntities"].Conectionstrings);

C# access to SQL Server database stored procedures and views

In my C# application I need access to a SQL Server database. But only to some views and some stored procedures. Is it advisable to use Entity Framework? Or are there some lightweight methods to get access?
Is it advisable to use entityframework?
Yes it is.
Or ore there some lightweight methods to get access?
That is what Entity Framework is i believe.
Entity Framework + LINQ to SQL = Magic.
ADO.NET is much faster than EF and there is no difficulty
using (SqlConnection conn = new SqlConnection("Data Source=.; Initial Catalog=DBNAME; Integrated Security=true;"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT ID, NAME FROM VIEWNAME where id > 4550;", conn))
{
// cmd.CommandType = CommandType.StoredProcedure // for SP
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
dictionary.Add(dr.GetInt32(0), dr.GetString(1));
}
}
}
}
Connection string better store in app.config

asp.net cannot open database login failed

I'm using the following to retrieve data from a database but the SqlConnection won't open. It throws an error at scon.Open(). I'm sure it's elementary but I can't work it out.
protected void Page_Load(object sender, EventArgs e) {
SqlConnection scon = new SqlConnection("Data Source = .\\SQLEXPRESS; Database = populate.mdf; Integrated Security = true; Initial Catalog = populate");
StringBuilder htmlString = new StringBuilder();
if(!IsPostBack)
{
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "SELECT * FROM populate";
scon.Open();
SqlDataReader articleReader = scmd.ExecuteReader();
htmlString.Append("'Populate page:'");
if (articleReader.HasRows)
{
while (articleReader.Read())
{
htmlString.Append(articleReader["dateTime"]);
htmlString.Append(articleReader["firstName"]);
htmlString.Append(articleReader["lastName"]);
htmlString.Append(articleReader["address"]);
htmlString.Append(articleReader["details"]);
}
populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() });
articleReader.Close();
articleReader.Dispose();
}
}
}
}
I'm using this link https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx as one of my references. I'm also using SQL Server 2008 R2 Express if these information are of any help.
Here's part of the error message:
SqlException (0x80131904): Cannot open database "populate" requested
by the login. The login failed.
Any help would be greatly appreciated.
Quoted from https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx#sse, if you want to use .mdf file as a database, you should use the following connection string containing AttacheDbFileName.
<add name="ConnectionStringName"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True" />
I solved it. All the connection string and other code was correct. The database just needed connecting to the Management Studio with some extra attention.

OleDB connection string for SQL Server in a C# program

I have seen lots of answers to connect to MS Access via OleDB but there is not good answer for SQL Server. I try to connect to a SQL Server database via OleDB provider in my C# program.
This is the connection string I am providing.
Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI
But it gives me error
‘Keyword not support ‘Provider’’
What I want to do here is connect database via OleDB in C# program.
This works as expected on my side. From the error message I strongly suspect that you are using the SqlConnection class instead of the OleDbConnection (Of course you need to use all the other classes provided by OleDb like OleDbCommand, OleDbDataReader etc...)
string connStr = "Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI";
using(OleDbConnection cnn = new OleDbConnection(connStr))
{
....
}
When in doubt, use the string builder in visual studio. That way unsupported keywords can't creep into your connection strings, the following is a wonderful example on how to use it.
http://www.c-sharpcorner.com/uploadfile/suthish_nair/how-to-generate-or-find-connection-string-from-visual-studio/
The same Connection string is working fine at my end.
I am posting my sample code which is executes successfully at my end
public string connStr = "Provider=SQLOLEDB;Data Source=.;Initial Catalog=<dbName>;Integrated Security=SSPI";
public OleDbConnection con;
protected void Page_Load(object sender, EventArgs e)
{
Test();
}
public void Test()
{
con = new OleDbConnection(connStr);
con.Open();
OleDbCommand cmd = new OleDbCommand("select * from tblApartments", con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
}
Please place breakpoint and check line to line and when your breakpoint comes to con.close(); then check ds, you can see the output.
The connection string you're using, considering the OLE DB provider, is correct. I didn't find any error in the connection string used, if you want to connect to a SQL Server data source.
Most probably, the reason of that error should be that you're not using correctly all the classes and objects required by the OLE DB provider, like OleDbCommand (that is similar to a SqlCommand but it's different), OleDbConnection, OleDbDataAdapter and so on. In a nutshell, the reason of that error should be this:
string connStr = "Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI";
using(SqlConnection scn = new SqlConnection(connStr))
{
....
}
Indeed, using a SqlConnection object, the ConnectionString property doesn't support the keyword Provider and, executing your application, you got an error about a keyword not supported.
Have a look at this simple tutorial about the use of OLE DB provider.

.Net C# how to connect to external SQL Server database ? OleDb or other?

Hi I would like to know how I should connect to the external SQL Server database in C# , .NET ?
For example if I have there parameters :
SQL info
Url to get to database (throughout browser also): Sqlweb.companyname.com
Database username: username
Server: Dcms-xxx
Databasename: databaseName
Databasepassword: password
?
I know how to connect to internal : Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.AppDomain.CurrentDomain.BaseDirectory + "..\\Files\\MapPlaces\\Database.mdb;";
But what about external ?
I have tried :
string nowConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Sqlweb.companyname.com;Initial Catalog = databaseName; User Id = Username; Password = Password;";
System.Data.OleDb.OleDbConnection dbcon = new System.Data.OleDb.OleDbConnection(nowConString);
string sql = "SELECT * FROM XXXTable";
dbcon.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sql, dbcon);
System.Data.OleDb.OleDbDataReader reader;
reader = cmd.ExecuteReader();
ScriptStuff.Append("Reader created!<br/>");
while (reader.Read())
{
string companyName = reader.GetValue(1).ToString();
ScriptStuff.Append(companyName+"<br/>");
}
Did not work ! Thank you for your help !
Edited from comments:
Yes that was one my mistake, thanks. Since first one was access and YES second is SQL Server. And it is SQL Server 2005. But I am new to .net and all that... I have found first one and second one in that connectionstring.com but I could not find or understand how to use that for this one ...
Could you help, and just post hole connection ? Thanks – Vilius 7 mins ago
I mean do I still need to use OleDB ? should there be "Provider=Microsoft.Jet.OLEDB.4.0;" in that connection string ? Where do i post what (server (that Dcms-xxx), or url of the sql server (sqlweb.companyname.com))? THANKS FOR YOUR HELP ! –
I would add a connectionString to my app/web.config.
<connectionStrings>
<add name="AspnetdbConnectionString"
connectionString="Data Source=<databaseadress>;Initial Catalog=<database>;User Id=<user>;Password=password>"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
The above example is how you specify an connectionstring for a MSSQL connection, and below a way to use this connectionstring.
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AspnetdbconnectionString"].ConnectionString))
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.Text;
cm.CommandText = "SELECT * FROM ...";
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
while (dr.Read())
{
// do stuff
}
}
}
}
Are you sure that it's a SQL Server database that you are trying to connect to?
Your "internal" example connects to a Microsoft Access database (OLEDB provider and database file extension .mdb)
If your external database is really a SQL Server database, the recommended way is using SqlConnection, SqlDataReader and so on instead of OleDbConnection etc.
Or, if you really want to use OleDb, you need a different connection string.
See connectionstrings.com (for SQL Server 2008, 2005 or 2000, depending what you're trying to connect to).
I would highly recommend taking a look at:
http://www.connectionstrings.com/
It's a quick, "in you face" treatment of the subject of connection strings for all major databases.

Categories