Execute select query from code behind - asp.net

How can i execute a SELECT query from my Code Behind file and then iterate through it?
I want to do something like this (just a simple pseudo example):
// SQL Server
var results = executeQuery("SELECT title, name FROM table");
foreach (var row in results)
{
string title = row.title;
string name = row.name;
}
How can i do this within code?

Something like this:
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["OrderID"], reader["CustomerID"]));
}
}
}
Source: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx
The connectionString will vary depending on the Database product and the authentication mechanism used (Windows Auth, username/password, etc.). The example above assumes you are using SQL Server. For a complete list of different ConnectionStrings, go to http://www.connectionstrings.com/

Related

Nested Queries In ASP.Net Without Async

I have the following code and basically I want it go step by step using the If statements. When I run this however I get this asp error: "This command requires an asynchronous connection. Set "Asynchronous Processing=true" in the connection string."
On this bit of code:
"addToTable.BeginExecuteReader();"
However I do not want it to by async I want it to run the subsequent queries only if the previous conditions are met.
Full code is below:
string dataset="";
if (System.Web.HttpContext.Current.Session["user"] != null)
{
if (name != null && carId != null)
{
using (SqlConnection con = new SqlConnection(st))
{
string getCar = "SELECT * FROM [Car] WHERE CarId = #carId";
SqlCommand cmd = new SqlCommand(getCarData, con);
cmd.Parameters.AddWithValue("#carId", carId);
using (cmd)
{
con.Open();
SqlDataReader data = cmd.ExecuteReader();
if (data.HasRows)
{
while (data.Read())
{
if (data["available"].ToString() == "0")
{
data.Close();
SqlCommand getParts = new SqlCommand("SELECT * FROM [CarCustomer] WHERE UserId = #UserId AND car=#carId", con);
getParts.Parameters.AddWithValue("#userId", System.Web.HttpContext.Current.Session["userId"]);
getParts.Parameters.AddWithValue("#carId", carId);
SqlDataReader grabRows = getParts.ExecuteReader();
if (grabRows.HasRows)
{
grabRows.Close();
SqlCommand updateTable = new SqlCommand("UPDATE [Table1] SET salesAmount=5 WHERE UserId=1", con);
updateTable.BeginExecuteReader();
}
else
{
grabRows.Close();
SqlCommand addToTable = new SqlCommand("INSERT INTO [Table1] (salesAmount) Values("1")", con);
addToTable.BeginExecuteReader();
}
dataset="good"
}
}
}
}
}
}
}
return dataset;
Instead of BeginExecuteReader command use SqlCommand.ExecuteNonQuery , because ExecuteNonQuery is used to perform query like insert,update and delete where as for Gettting data Read method is used.
one more thing BeginExecuteReadermethod is used to perfrom asncy read operation so if you dont want that than just use ExecuteReadermethod to get data.
Read SqlCommand.ExecuteNonQuery -
You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.

how to do a insert statement in web service asp.net

i am suppose to receive the data from android to my web service and my web service is going to insert the data into my data base. how am i going to do about it to insert the data from my web service to database.
this is my start of code :
[WebMethod]
public StudentTransactions GetStudentTransactions(string Name, string CLass, string NRIC, int StallNo, float AmountSpent)
{
SqlCommand sql1 = new SqlCommand("INSERT Into StudentTransactions (Name, CLass,NRIC,StallNo,AmountSpent) VALUES (Name,CLass,NRIC,StallNo,AmountSpent)");
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ncpsdbbConnectionString2"].ConnectionString))
{
conn.Open();
{
}
}
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ncpsdbbConnectionString2"].ConnectionString))
{
SqlCommand command = new SqlCommand("INSERT Into StudentTransactions (Name, CLass,NRIC,StallNo,AmountSpent) VALUES (#Name,#CLass,#NRIC,#StallNo,#AmountSpent)");
command.Connection.Open();
command.ExecuteNonQuery();
}
Add the values and params like so:
command.Parameters.AddWithValue("#ParamName", [Some Value]);
Try the above.
Read more here:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx

connect to Access database in asp.net and Join statement

Let say there is an Asp.ne5 3.5 web application with an Access database. The database has two tables like this:
In some pages I can get the username with `"page.users.identity.name". In this Application, each user can create so many pages. My question is how to write a statement to get pages created with specific username (the Group_ID in joined).
NOTE: This is what i tried and i got "error reading database".
SELECT Pages.* FROM
Pages INNER JOIN Users ON Pages.Group_ID = Users.Group_ID
WHERE Users.Username = page.users.identity.name
Have you tried using a parametrized query:
public ActionResult SomeAction()
{
// get the username of the currently connected user
string username = User.Identity.Name;
string cs = WebConfigurationManager.ConnectionStrings["MyConnStr"].ConnectionString;
using (var conn = new OleDbConnection(cs))
using (var cmd = conn.CreateCommand())
{
conn.Open();
var sql =
#"SELECT Pages.* FROM Pages
INNER JOIN Users
ON Pages.Group_ID = Users.Group_ID
WHERE Users.Username = ?";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("Username", username);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
...
}
}
}
...
}
Try with this query,
SELECT Pages.* FROM
Pages,Users where Pages.Group_ID = Users.Group_ID
and Users.Username = page.users.identity.name
I Missed the Single quote "' " in the statement for page.users.identity.name. now this should be like this:
dim lasts as string= "'"
"SELECT Pages.* FROM
Pages INNER JOIN Users ON Pages.Group_ID = Users.Group_ID
WHERE Users.Username ='" & page.users.identity.name & lasts

how to use the passed parameters to the asp.net webservice in a sql statement?

hello i build a webservice to communicate with the iPhone.
i want to display the rooms from the selected street in a table, to do that i must to pass some id's from my iPhone with JSON to the sql database over a asp.net webservice.
my webmethod look like this:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public string Room(string street_id, string country_id, string city_id)
{
return RoomHelper.Room(street_id, country_id, city_id);
}
My sql statement should look like this:
SELECT Roomname FROM Room WHERE street_id = (passed street_id) AND country_id = (passed country_id) AND city_id = (passed city_id)
how can i use the passed parameters in my sql statement to filter the rooms ?
using (SqlConnection conn = new SqlConnection("<my connection string>"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Roomname FROM Room WHERE street_id = #streetId AND country_id = #countryId AND city_id = #cityId", conn))
{
cmd.Parameters.AddWithValue("#streetId", street_id);
cmd.Parameters.AddWithValue("#countryId", country_id);
cmd.Parameters.AddWithValue("#cityId", city_id);
using (var reader = cmd.ExecuteReader())
{
// retrieve your data per row or as you wish
while (reader.Read())
{
}
}
}
}

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