Calling a stored procedure with asp.net - asp.net

If I have a connection string defined in my web.config file, how do I create a connection to the SQL db from C# code (sorry forgot to specify) and then call a stored procedure. I would then like to eventually use this data in some way as my DataSource for a GridView.
Here is how the connection string is defined in the web.config:
<connectionStrings>
<add name="db.Name" connectionString="Data Source=db;Initial Catalog=dbCat;User ID=userId;Password=userPass;" providerName="System.Data.SqlClient" />
</connectionStrings>
The db server is a Microsoft SQL server.
Here is what I was looking for:
ConnectionStringSettings conSet = ConfigurationManager.ConnectionStrings["db.Name"];
SqlConnection con = new SqlConnection(conSet.ConnectionString);
The code to get the data is fairly trivial. I was more interested in accessing it from a connectionString variable in the web.config file.

If it's a resource file like so:
private static readonly string connString = Resource1.connString;
Where connString is the name of the key. If it is a web.config file
Something like so:
private static readonly string connString = System.Configuration.ConfigurationManager.AppSettings["strConn"]; where conn is defined in your web config file.
<add key="strConn" value="User ID=test;Password=test;Initial Catalog=TestDB;Data Source=NameOfServer;"/>
Then call the sproc:
//connString = the string of our database app found in the resource file
using (SqlConnection con = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("EMPDLL_selClientByClientID", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ClientID", SqlDbType.VarChar).Value = cID;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
if (reader.Read())
{
//more code
}
}
}
}
}
That's if you are coding in C#, VB.net its the same deal just a bit more wordier :), here's a small sample:
Public Sub DeleteEmployee(ByVal lVID As Long)
Dim conMyData As SqlConnection
Dim cmdDelete As SqlCommand
Try
conMyData = New SqlConnection(connString)
cmdDelete = New SqlCommand("delEmployee", conMyData)
With cmdDelete
.CommandType = CommandType.StoredProcedure
'add the parameters
.Parameters.Add("#LoginID", SqlDbType.BigInt).Value = lVID 'the request
conMyData.Open() 'open a connection
.ExecuteNonQuery() 'execute it
End With
Catch ex As Exception
Throw ex
Finally
cmdDelete = Nothing
conMyData.Close()
conMyData = Nothing
End Try
End Sub
Of course you should use a using statement instead of try/catch/finally to ensure you clean up your resources that are being used.

Something like this...
using (var con = new SqlConnection(_connectionString))
{
using (var cmd = new SqlCommand(_storedProcedureName, con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#pMyParamater", myParamaterValue);
con.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// do something with the row
}
}
}
}
This is all pretty simple stuff to be honest, you should be able to find everything you need from the ADO.NET documentation

Related

How to use multiple SqlDataReader in ASP.NET

I use SqlDataReader connection1 inside that I use another SqlDataReader connection2. So connection open issue occurring connection1 open. How to resolve it? Kindly provide a solution
First create different connection, datareader... object
and close the connection datareader if data not read
example code
string connectionString1 = "Data Source=localhost;Integrated security=SSPI;Initial Catalog=AdventureWorks;";
string connectionString2 = "Data Source=localhost;Integrated security=SSPI;Initial Catalog=AdventureWorks;";
//Create the command
string sqlSelect1 = "SELECT TOP 5 CustomerID, AccountNumber FROM Sales.Customer";
string sqlSelect2 = "SELECT TOP 5 CustomerID, AccountNumber FROM Sales.Customer";
//open the connection
SqlConnection objConn1 = new SqlConnection(connectionString1);
SqlConnection objConn2 = new SqlConnection(connectionString2);
// Create the command and open the connection
SqlCommand objcommand1 = new SqlCommand(sqlSelect1, objConn1);
SqlCommand objcommand2 = new SqlCommand(sqlSelect2, objConn2);
objConn1.Open();
objConn2.Open();
// Create the DataReader to retrieve data
SqlDataReader DR1 = objcommand1.ExecuteReader())
SqlDataReader DR2 = objcommand2.ExecuteReader())
while (DR1.Read())
{
if(DR2.Read())
{
//YOUR CODE
}
else
{
DR2.Close();
}
}
DR1.Close();
DR2.Close();
objConn1.Close();
objConn2.Close();

How do I write SQL connection string?

I have this as my connection string property:
Data Source="c:\users\perdanny\documents\visual studio 2012\Projects\WebApplication1\WebApplication1\App_Data\Users.sdf"
Now, how should I write it in my code:
sqlConnection = new SqlConnection(???);
try this:
string strConnection = ConfigurationManager.ConnectionStrings["Name of connection string key"].ConnectionString;
// Or, for a quick test you could also use
// string strConnection = "Data Source = c:\\users\\perdanny\\documents\\visual studio 2012\\Projects\\WebApplication1\\WebApplication1\\App_Data\\Users.sdf"
using (var conn = new SqlCeConnection(string.Format("Data Source={0}", strConnection)))
{
conn.Open();
try
{
System.Data.SqlServerCe.SqlCeCommand cmd = System.Data.SqlServerCe.SqlCeCommand;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "Your sql stored proc name";
cmd.Connection = conn ;
cmd.ExecuteNonQuery();
}
catch (SqlCeException)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
string connStr = ConfigurationManager.ConnectionStrings["connectionString"].ToString();
<add name="connectionString" connectionString="Data Source=SQLEXPRESS;Initial Catalog=dbsql;User ID=hello;Password=hello"
providerName="System.Data.SqlClient" />
use ConfigurationManager and
look at below code line:
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;

Invalid attempt to call Read when reader is closed

I'm kind of struggling trying to get this datagrid to bind. Everytime I run my code, I get an error message stating, "Invalid attempt to call Read when reader is closed". I don't see where I am closing my reader. Can you please help me? My code for loading the datagrid is below:
protected void LoadGrid()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["VTC"].ConnectionString;
conn.Open();
string sql = "select * from roi_tracking";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataReader sqlReader = cmd.ExecuteReader())
{
gridROI.DataSource = sqlReader;
gridROI.DataBind();
sqlReader.Dispose();
cmd.Dispose();
}
}
}
}
You can't use a SqlDataReader as a DataSource for a DataGrid.
From MSDN:
A data source must be a collection that implements either the
System.Collections.IEnumerable interface (such as
System.Data.DataView, System.Collections.ArrayList, or
System.Collections.Generic.List(Of T)) or the IListSource interface to
bind to a control derived from the BaseDataList class.
Datasource property:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basedatalist.datasource.aspx
SqlDataReader:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx
A common methodology to bind the query results to your datagrid would be to use a SqlDataAdapter to fill a DataTable or DataSet and then bind that to your DataGrid.DataSource:
protected void LoadGrid()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["VTC"].ConnectionString;
conn.Open();
string sql = "select * from roi_tracking";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill((DataTable)results);
gridROI.DataSource = results;
}
}
}
In addition to what pseudocoder said, you wouldn't want to bind to a SqlDataReader anyway: the connection to the database will remain open so long as the reader instance exists.
You definitely want to deserialize the data into some other disconnected data structure so that you release the connection back into the pool as quickly as possible.

How to use created connection string of Web.Config in my C# asp.net 4.0 project?

Actually I am new in this topic so required some help.
I have added connection string in Web.Config
<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
and know that, to use it I have to put this statement in my C# code behind
string connStr = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
That's all I know.
My Question is
What should I do if I want to execute some query for my aspnetdb.mdf dataabase (Built in db of ASP.NET built in login contols in Visual Studio 2010)
Earlier, I was doing this to accomplish my task
1) No connection string in Web.Config. and
2) Hard code in codebehind
SqlConnection con = new SqlConnection("data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true");
SqlCommand cmd = new SqlCommand();
protected void btnnameedit_Click(object sender, EventArgs e)
{
try
{
con.Open();
cmd.CommandText = "update tamhankarnikhil set fname = '" + fname.Text + "'";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
fname.Text = "";
}
catch (Exception a)
{
Response.Write(a.Message);
}
}
Here's what you could do:
protected void btnnameedit_Click(object sender, EventArgs e)
{
try
{
string connStr = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
using (var conn = new SqlConnection(connStr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "UPDATE tamhankarnikhil SET fname = #fname";
cmd.Parameters.AddWithValue("#fname", fname.Text);
cmd.ExecuteNonQuery();
fname.Text = "";
}
}
catch (Exception a)
{
Response.Write(a.Message);
}
}
You will notice the usage of parametrized queries to avoid SQL injection to which your code was vulnerable to due to the string concatenations you were using when constructing the SQL query.
You will also notice that the SqlConnection and SqlCommand are wrapped in using statements to ensure their proper disposal even in the event of an exception.

Asp.Net select in Sql

This is going to be very simple I know. I have seen so many different ways of using sql in asp.net with no real standard. What I want to know is how to cleanly select from an sql database in asp.net and retrieve multiple records. For example: select all userids.
String sql =
"SELECT [UserId] FROM [UserProfiles] WHERE NOT [UserId] = 'CurrentUserId'";
string strCon = System.Web
.Configuration
.WebConfigurationManager
.ConnectionStrings["SocialSiteConnectionString"]
.ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
/*
This is where I need to know how to retrieve the information from the
above command(comm). I am looking for something similiar to php's
mysql_result. I want to access the records kind of like an array or some
other form of retrieving all the data.
Also when the new SqlCommand is called...does that actual run the
SELECT STATEMENT or is there another step.
*/
conn.Close();
I think that this is what you are looking for.
String sql = "SELECT [UserId] FROM [UserProfiles] WHERE NOT [UserId] = 'CurrentUserId'";
string strCon = System.Web
.Configuration
.WebConfigurationManager
.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader nwReader = comm.ExecuteReader();
while (nwReader.Read())
{
int UserID = (int)nwReader["UserID"];
// Do something with UserID here...
}
nwReader.Close();
conn.Close();
I do have to say, though, that the overall approach can use a lot of tuning. First, you could at least start by simplifying access to your ConnectionString. For example, you could add the following to your Global.asax.cs file:
using System;
using System.Configuration;
public partial class Global : HttpApplication
{
public static string ConnectionString;
void Application_Start(object sender, EventArgs e)
{
ConnectionString = ConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
}
...
}
Now, throughout your code, just access it using:
SqlConnection conn = new SqlConnection(Global.ConnectionString);
Better yet, create a class in which the "plumbing" is hidden. To run the same query in my code, I'd just enter:
using (BSDIQuery qry = new BSDIQuery())
{
SqlDataReader nwReader = qry.Command("SELECT...").ReturnReader();
// If I needed to add a parameter I'd add it above as well: .ParamVal("CurrentUser")
while (nwReader.Read())
{
int UserID = (int)nwReader["UserID"];
// Do something with UserID here...
}
nwReader.Close();
}
This is just an example using my DAL. However, notice that there is no connection string, no command or connection objects being created or managed, just a "BSDIQuery" (which does lots of different things in addition to that shown). Your approach would differ depending on the tasks that you do most often.
Most of the time, I use this (note that I am also using a connection pooling approach):
public DataTable ExecuteQueryTable(string query)
{
return ExecuteQueryTable(query, null);
}
public DataTable ExecuteQueryTable(string query, Dictionary<string, object> parameters)
{
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = query;
if (parameters != null)
{
foreach (string parameter in parameters.Keys)
{
cmd.Parameters.AddWithValue(parameter, parameters[parameter]);
}
}
DataTable tbl = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(tbl);
}
return tbl;
}
}
}
Here's an adaption of your existing code:
String sql = "SELECT [UserId] FROM [UserProfiles] WHERE [UserId] != #CurrentUserId";
string strCon = System.Web
.Configuration
.WebConfigurationManager
.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
DataTable result = new DataTable();
using (var conn = new SqlConnection(strCon))
using (var cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#CurrentUserID", SqlDbType.Int).Value = CurrentUserID;
conn.Open();
result.Load(cmd.ExecuteReader());
}
Creating a SqlCommand doesn't execute it at all.
The command will be executed when you call ExecuteReader or something similar.
If you want something which will fetch all the results into memory, you should be looking at DataSet/DataTable. There's a tutorial for them here - or there are plenty of others on the net, and any decent ADO.NET book will cover them too.
If you don't want to fetch them all into memory at once, then ExecuteReader it the method for you. That will return a SqlDataReader which is like a database cursor - it reads a row at a time, and you ask for individual columns as you want them, calling Read to get to the next row each time.
Whereas in PHP you'd do something like,
while ($row = mysql_fetch_array ($result))
{
//this assumes you're doing something with foo in loop
$foo = $row["userid"];
//using $foo somehow
}
in .NET, you do something different. Believe me, originating from a PHP background, the transition from PHP to .NET is not easy. There's a lot of things that will seem bizarre. After a while though, it will make sense! Just stick it out. I personally like it better.
Ok.. assuming you have a DataSet like you say, you can do something like this,
//assuming you have a DataSet called myDataSet
for (int i = 0; i < myDataSet.Tables[0].Rows.Count; i++)
{
//likewise assuming here you're doing something with foo in loop
string foo = myDataSet.Tables[0].Rows[i]["userid"].ToString();
//similarly do something with foo in loop
}
That does the same thing as the PHP snippet.

Resources