Adding '% into SQL Command - asp.net

I have an SQL Query that i want to run throw my asp.net (WebForms) Project
The Query is:
SELECT COUNT([order]) FROM menu_orders_Finished
WHERE [order] LIKE '%EXAMPLE%'
What i'm trying to do is
con.Close();
con.Open();
cmd = new SqlCommand("select * from menu",con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
Series series = Chart2.Series["Series2"];
while (dr.Read())
{
search = new SqlCommand("SELECT COUNT([order]) FROM menu_orders_Finished WHERE [order] LIKE '%#order#%'", con);
search.Parameters.AddWithValue("#order", dr["name"].ToString());
int count = Convert.ToInt32(search.ExecuteScalar());
Label3.Visible = true;
Label3.Text += count.ToString() + "+";
}
con.Close();
Which is Basically Counting how many times i'm having an order with one my menu items in the order (I want to make a chart of the best selling meal)
And then adding it in the chart (But i toke it off just to see what i get first)

I think you want string concatenation:
search = new SqlCommand("SELECT COUNT([order]) FROM menu_orders_Finished WHERE [order] LIKE CONCAT('%', #order, '%')", con);

Related

Select SQL Server table data using ASP.NET

I want to select/retrieve all data from SQL Server using ASP.NET.
I've tried this code...
SqlCommand cmdd = new SqlCommand("select * from comment where ID='" + st + "'", con);
SqlDataReader drr;
drr = cmdd.ExecuteReader();
while(drr.Read())
{
user_name.Text = drr["Username"].ToString();
date.Text = drr["Date_Created"].ToString();
userrcomment.Text = drr["Comment"].ToString();
}
The code works fine but it can select only one record from database but I want to select all the records...
Also can any one tell me that how to use two/multiple queries using only one data reader....
Any help will be appreciated...
Update: problem is when the query run then only the last record will show, but I want that all the record will show against the mentioned id...
Update 2 this is my page code, as I am new in asp.net, so how can I get the username and other data in span or p tag...
<asp:Panel ID="Panel1" runat="server" Height="140px" Width="378px">
<p>
<asp:Label ID="user_name" runat="server"></asp:Label> Commented on <asp:Label ID="date" runat="server"></asp:Label></p>
<asp:Label ID="userrcomment" runat="server" Height="31px" Width="378px"></asp:Label>
</asp:Panel>
If you are getting only one records then there are two possibilities.
"select * from comment where ID='" + st + "'" In your where condition satisfy for only one record.
You are using SqlDataReader in while loop if there are many records you got but you can only see last record bcoz it will be overwrite last record in every loop.
while(drr.Read())
{
user_name.Text = drr["Username"].ToString();
date.Text = drr["Date_Created"].ToString();
userrcomment.Text = drr["Comment"].ToString();
}
the user_name.Text will replaced with last record.
Assuming your code is otherwise working, and you want to see all the data in just the three text boxes instead of some more tabular format.
SqlCommand cmdd = new SqlCommand("select * from comment where ID='" + st + "'", con);
SqlDataReader drr;
drr = cmdd.ExecuteReader();
while(drr.Read())
{
user_name.Text += drr["Username"].ToString();
date.Text += drr["Date_Created"].ToString();
userrcomment.Text += drr["Comment"].ToString();
}
Notice instead of overwriting the value of the textbox, I'm appending strings to it because I used +=. You might want to concatenate a , to it also.
More likely with multiple records though, you want to have them get in a table. The easiest and most straightforward way to do this is:
Code Behind
var cmd = new SqlCommand("select * from comment where ID=#id");
cmd.Parameters.AddWithValue("id", st);
var dt = new DataTable();
using(var con = new SqlConnection(connectionString))
{
con.Open();
dt.Load(cmd.ExecuteReader());
}
GridView1.DataSource = dt;
GridView1.DataBind();
Markup
<asp:GridView runat="server" id="GridView1" AutoGenerateColumns="true" />
You can execute multiple select queries using a single DataReader. There is an article namely,"Executing multiple SQL statements as one against SQL Server" in CodeProject. Please read it, you will get solution for sure.
using(SqlConnection conn=new SqlConnetion(ConnectionString))
{
using(SqlCommand cmdd = new SqlCommand("select * from comment where ID='" + st + "'", con))
{
using(SqlDataAdapter adapter=new SqlDataAdapter(cmdd))
{
DataTable dt=new DataTable();
adapter.Fill(dt);
//Bind the datasource with a repeater control in which you can place textbox control. It will repeat for every data rows.
}
}
}
You need to place the record into a dataset for you to get all the data you're trying to Retrieve
SqlCommand cmdd = new SqlCommand("select * from comment where ID='" + st + "'", con);
SqlDataReader drr = new SqlDataReader(cmdd);
DataSet ds = new DataSet();
da.Fill(ds);
foreach(DataRow dr in ds.Tables[0].Rows)
{
user_name.Text = dr["Username"].ToString();
date.Text = dr["Date_Created"].ToString();
userrcomment.Text = dr["Comment"].ToString();
}
select/retrieve all data from SQL-Server using ASP.NET
using this SqlDataReader (sqldr) GetValue for all the records
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringsName"].ConnectionString);
string sql = "select * from comment where ID='" + st + "'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sqldr = cmd.ExecuteReader();
if (sqldr.Read() == true)
{
user_name.Text = sqldr.GetValue(2).ToString();
date.Text = sqldr.GetValue(3).ToString();
userrcomment.Text = sqldr.GetValue(4).ToString();
}
sqldr.Close();
con.Close();

Response.write only shows the first record from the database (this.session.sessionid)

I've got a problem for the past few days. I will explain short what i've did.
I have a table created in the database called 'Cart'. This Cart cointains: ClientID, Artical number, and quantity. In the ClientID, a session.sessionID stored. In the Artical just a number like 1012. And in quantity a number like 1 or 3.
What I would like to, is retrieve all the records, with the session.session id of the user.
It does work in the page, but only the first record of the like 4-5 records that are in the cart table is shown. I think i comes due the problem that it looks for this.session.sessionidand when it found one, it doesn't look any further then that.
I've tried to loop through the query where sessions is. But it won't let me loop because it doesn't know for? Even if I loop the whole query outside of it like this:for (int i = 0; i < sessies.Length; i++) It will show more records.. but they are all the first records.. I know that was a stupid try but I can always try..
Looked for all over the internet but couldn't find the solution to this.
Hope to get a response soon from somebody. It would be gratefull.
Used the following code:
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["GarageConnectionString"].ToString()))
{
string sessions = this.Session.SessionID;
SqlCommand cmd = new SqlCommand("SELECT * FROM cart where ClientID='" + sessions + "'", cn);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
TextBox1.Text = rdr[2].ToString();
Response.Write("<br>" + ("Sessie id "+rdr[1].ToString()));
Response.Write("<br>" + ("Artikel nummer "+rdr[2].ToString()));
Response.Write("<br>" + ("Aantal "+rdr[3].ToString()));
cn.Close();
}
SqlDataReader advances to the next record in the set: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read%28v=vs.110%29.aspx
Call Read() in a loop, like so:
using (SqlConnection cn = newSqlConnection(ConfigurationManager.ConnectionStrings["GarageConnectionString"].ToString()))
{
string sessions = this.Session.SessionID;
SqlCommand cmd = new SqlCommand("SELECT * FROM cart where ClientID='" + sessions + "'", cn);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
TextBox1.Text = rdr[2].ToString();
Response.Write("<br>" + ("Sessie id "+rdr[1].ToString()));
Response.Write("<br>" + ("Artikel nummer "+rdr[2].ToString()));
Response.Write("<br>" + ("Aantal "+rdr[3].ToString()));
}
cn.Close();
}
You should loop through the datareader: ie:
while (rdr .Read())
{
Console.WriteLine("{0}\t{1}", rdr .GetInt32(0),
rdr .GetString(1));
}
Each call to SqlDataReader.Read() gets a single row, unless there are no more rows when it returns false.
So you need to loop to get all rows:
while (rdr.Read()) {
// Use rdr methods to access the values from the current row.
}
Use While Loop- Example
if (rdr .HasRows)
{
while (rdr .Read())
{
Console.WriteLine("{0}\t{1}", rdr .GetInt32(0),
rdr .GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
rdr .Close();

multiple SQL commands. Good style?

I got an asp.net application running perfectly fine. in my code i have the following lines
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand getGenreId = new SqlCommand("Select ID from tblGenre WHERE Genre=#newGenre;", con);
getGenreId.Parameters.AddWithValue(#"newGenre", newGenre);
SqlCommand cmd = new SqlCommand("UPDATE tblSong SET Title=#newTitle, ArtistId=#newArtistId, GenreId=#newGenreId WHERE (ID = #songId);", con);
cmd.Parameters.AddWithValue(#"newTitle", newTitle);
cmd.Parameters.AddWithValue(#"newArtistId", newArtistId);
cmd.Parameters.AddWithValue(#"songId", songId);
con.Open();
newGenreId = (int)getGenreId.ExecuteScalar();
cmd.Parameters.AddWithValue(#"newGenreId", newGenreId);
cmd.ExecuteNonQuery();
}
i know database connections are valuable resources and i should be careful when using them. (open as late as possible and make sure they will be closed aswell)
My question now is this code considered bad style because im opening the connection then have as sql query to get an ID and then have another sql query to insert a record.
thanks you!
If you convert to using stored procedure, you can eliminate 1 round trip, therefore reducing network traffic and possibly increase performance.
using (SqlCommand cmd = new SqlCommand("Update_tblSong", con);
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#newGenre", newGenre);
cmd.Parameters.AddWithValue("#newTitle", newTitle);
cmd.Parameters.AddWithValue("#newArtistId", newArtistId);
cmd.Parameters.AddWithValue("#songId", songId);
cmd.ExecuteNonQuery();
}
Proc will be like this, I estimated on your variable size.
CREATE PROC Update_tblSong
(
#newGenre VARCHAR(25)
,#newTitle VARCHAR(50)
,#newArtistID INT
,#songID INT
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #NewGenreID INT;
SELECT #NewGenreID = ID
FROM tblGenre
WHERE Genre = #newGenre;
UPDATE tblSong
SET Title = #newTitle
,ArtistId = #newArtistId
,GenreId = #NewGenreID
WHERE ( ID = #songId )
END;
Overall your code flow seems fine, you are using a single connection to execute multiple (related) commands.
You can improve it further with enclosing your command objects in using statement. Since they implement IDisposable interface, just like your connection object.
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
using (SqlCommand getGenreId = new SqlCommand("Select ID from tblGenre WHERE Genre=#newGenre;", con))
{
getGenreId.Parameters.AddWithValue(#"newGenre", newGenre);
newGenreId = (int)getGenreId.ExecuteScalar();
}
using (SqlCommand cmd = new SqlCommand("UPDATE tblSong SET Title=#newTitle, ArtistId=#newArtistId, GenreId=#newGenreId WHERE (ID = #songId);", con))
{
cmd.Parameters.AddWithValue(#"newTitle", newTitle);
cmd.Parameters.AddWithValue(#"newArtistId", newArtistId);
cmd.Parameters.AddWithValue(#"songId", songId);
cmd.Parameters.AddWithValue(#"newGenreId", newGenreId);
cmd.ExecuteNonQuery();
}
}
Why not use a single query with a subquery for your SQL?
UPDATE tblSong SET Title = #newTitle, ArtistId = #newArtistId, GenreId = (Select top 1 ID from tblGenre WHERE Genre=#newGenre ORDER BY Genre) WHERE (ID = #songId);

How to connect to multiple databases in asp.net using SqlDataReader?

How to connect to multiple databases in asp.net using SqlDataReader?
Assume that I have two databases such as “Product” and “people”. The product database has two tables, let’s say table1 and table 2, while people has two tables, let’s say again table1 and table2.
I want to get some information from Product.table1 and some from people.table2.
I tried with the following code, but unfortunately it does not work:
SqlConnection con1 = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Product.mdf;Integrated Security=True");
SqlConnection con2 = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\People.mdf;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand("select prod_name, prod_price from product_tbl", con1);
SqlCommand cmd2 = new SqlCommand("select std_name from student_tbl", con2);
con1.Open();
con2.Open();
SqlDataReader dr1 = cmd1.ExecuteReader();
SqlDataReader dr2 = cmd2.ExecuteReader();
// GridView1.DataSource = How to do it??
GridView1.DataBind();
You can either do it as follow :
Retrieve the result from Product DB in dataset1
Retrieve the result from People DB in dataset2
Use DataSet.Merge Method to merge the two data sets in a single dataset say dsProductPeople
Bind dsProductPeople to the grid
OR you can use following example :
// Assumes that customerConnection is a valid SqlConnection object.
// Assumes that orderConnection is a valid OleDbConnection object.
SqlDataAdapter custAdapter = new SqlDataAdapter(
"SELECT * FROM dbo.Customers", customerConnection);
OleDbDataAdapter ordAdapter = new OleDbDataAdapter(
"SELECT * FROM Orders", orderConnection);
DataSet customerOrders = new DataSet();
custAdapter.Fill(customerOrders, "Customers");
ordAdapter.Fill(customerOrders, "Orders");
DataRelation relation = customerOrders.Relations.Add("CustOrders",
customerOrders.Tables["Customers"].Columns["CustomerID"],
customerOrders.Tables["Orders"].Columns["CustomerID"]);
foreach (DataRow pRow in customerOrders.Tables["Customers"].Rows)
{
Console.WriteLine(pRow["CustomerID"]);
foreach (DataRow cRow in pRow.GetChildRows(relation))
Console.WriteLine("\t" + cRow["OrderID"]);
}

asp.net insert data into DB

con.Open();
cmd2 = new SqlCommand("insert into dailyWorkout('"+RadioButton1.Text+"', '"+RadioButton2.Text+"', '"+RadioButton3.Text+"', '"+RadioButton4.Text+"', '"+RadioButton5.Text+"', '"+Label1.Text+"')", con);
cmd2.ExecuteNonQuery();
Hey guys, been working on this website for a while, but I get an error when putting data into the database saying
Incorrect syntax near ')'.
With other stuff that I'm putting same way it works and this does not.
You should really really REALLY use parametrized queries to avoid SQL injection (and to boost performance; and avoid issues with type conversions etc.)
So I would recommend using code something like this:
// define your *parametrized* SQL statement
string insertStmt = "INSERT INTO dbo.YourTable(Col1, Col2, Col3) VALUES(#Val1, #Val2, #Val3);";
// put SqlConnection and SqlCommand into "using" blocks to ensure proper disposal
using(SqlConnection conn = new SqlConnection("-your-connection-string-here-"))
using(SqlCommand cmd = new SqlCommand(insertStmt, conn))
{
// set the parameters to the values you need
cmd.Parameters.AddWithValue("#Val1", "Some String here");
cmd.Parameters.AddWithValue("#Val2", 42);
cmd.Parameters.AddWithValue("#Val3", DateTime.Today.AddDays(-7));
// open connection, execute query, close connection right away
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
}
Points to remember:
ALWAYS use parametrized queries - do NOT concatenate together your SQL statements!
put the SqlConnection and SqlCommand into using(...) { ... } blocks to ensure proper disposal
always explicitly define the list of columns you want to use in a SELECT and also an INSERT statement
open connection as late as possible, execute query, close connection again right away
That will do the job but I strongly advice using Parameters.
con.Open();
cmd2 = new SqlCommand("insert into dailyWorkout values ('"+RadioButton1.Text+"', '"+RadioButton2.Text+"', '"+RadioButton3.Text+"', '"+RadioButton4.Text+"', '"+RadioButton5.Text+"', '"+Label1.Text+"')", con);
cmd2.ExecuteNonQuery();
Instead of the code above you'd better to use
cmd2 = new SqlCommand("insert into dailyWorkout values (#val1, #val2, #val3,#val4,#val5,#val6)", con);
cmd2.Parameters.AddWithValue("#val1",RadioButton1.Text);
cmd2.Parameters.AddWithValue("#val2",RadioButton2.Text);
cmd2.Parameters.AddWithValue("#val3",RadioButton3.Text);
cmd2.Parameters.AddWithValue("#val4",RadioButton4.Text);
cmd2.Parameters.AddWithValue("#val5",RadioButton5.Text);
cmd2.Parameters.AddWithValue("#val6",Label1.Text)
cmd2.ExecuteNonQuery();
Ok its already been mentioned, don't inject parameters like that.
But if you must, the problem is that your final sql string looks like:
insert into dailyWorkout('string1', 'string2', 'string3', 'string4', 'string5', 'string6')
when it should be
insert into dailyWorkout(columnName1,columnName2,columnName3,columnName4,columnName5,columnName6)
values('string1', 'string2', 'string3', 'string4', 'string5', 'string6')
But you should really consider:
var sqlCmd = new SqlCommand("insert into dailyWorkout(columnName1,columnName2,columnName3,columnName4,columnName5,columnName6) values(#v1, #v2, #v3, #v4, #v5, #v6)", default(SqlConnection));
sqlCmd.Parameters.Add("#v1", SqlDbType.NVarChar).Value = RadioButton1.Text;
sqlCmd.Parameters.Add("#v2", SqlDbType.NVarChar).Value = RadioButton2.Text;
sqlCmd.Parameters.Add("#v3", SqlDbType.NVarChar).Value = RadioButton3.Text;
sqlCmd.Parameters.Add("#v4", SqlDbType.NVarChar).Value = RadioButton4.Text;
sqlCmd.Parameters.Add("#v5", SqlDbType.NVarChar).Value = RadioButton5.Text;
sqlCmd.Parameters.Add("#v6", SqlDbType.NVarChar).Value = Label1.Text;
sqlCmd.ExecuteNonQuery();

Resources