Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this code
public static DataSet tipopromocion(string id_edificio,string date_from, string date_to)
{
DataSet tipo = new DataSet();
MySqlConnection con = new MySqlConnection(connectionstring);
string tipo_promo = "select pr.tipo_promocion from promocion_edificio pe inner join inventario i on i.id_edificio = pe.id_edificio inner join promocion pr on pe.id_promocion=pr.id_promocion where i.id_edificio = '" + id_edificio + "' and i.fecha between '" + date_from + "' and Date_Sub('" + date_to + "',interval 1 Day) and i.fecha between pe.inicio_promo AND pe.fin_promo and date(now()) between pe.inicio_alojamiento and pe.fin_alojamiento AND ( FIND_IN_SET('A',pe.tipo)) group by pe.id_promocion order by pr.valor_promocion desc";
MySqlCommand cmd13 = new MySqlCommand(tipo_promo, con);
MySqlDataAdapter da13 = new MySqlDataAdapter(cmd13);
da13.Fill(tipo);
return tipo;
}
tipo_promonic
-------------
porcentaje
porcentaje
fixed
discount
porcentaje
discount
discount
fixed
fixed
porcentaje
porcentaje
the above result like above table table ok now i am trying to check in "tipo_promonic" column contains some rows so i am checking if "tipo_promonic" column contains porcentaje,fixed,discount then go to some function else it goto another function ok but in "tipo_promonic" column contains many duplicate values so how to check the condition. please help me out from this problem.
Try Re-framing your SQL query using DISTINCT keyword to avoid Duplicate record
string tipo_promo = "select DISTINCT pr.tipo_promocion from promocion_edificio pe inner ..."
Try using DataReader
MySqlConnection con = new MySqlConnection(connectionstring);
string tipo_promo = "select DISTINCT pr.tipo_promocion from promocion_edificio pe inner.."
MySqlCommand cmd13 = new MySqlCommand(tipo_promo, con);
DataReader dr = cmd13.ExecuteReader();
while(dr.Read())
{
if(dr[0].ToString() == "YourOption")
{//Do this;}
}
This is for a data table. You can make out for DataAdapter or Dataset according to your need. This is basically a loop which checks each row for a value of a particular column.
foreach (DataRow dr in dataTable.Rows)
{
if (dr["typo_promonic"].Equals("porcentaje"))
{
//your code here.
}
else if (dr["tipo_promonic"].Equals("discount"))
{
//your code here.
}
else
{
//your code here.
}
}
You can add more else...if as per your options. Whatever you want to do, you can do in those code blocks.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a created a GridView in ASP.NET which is databound to a stored procedure.
In my stored procedure I have customerID which is from another table. How I can display name of the customer instead of the id number? Could anyone help me please?
This my code
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("usp_Counry"))
{
cmd.Parameters.AddWithValue("#Action", "SELECT");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
you may use join or subquery in your stored procedure to get customers' names if both tables have CustomerId column (column names may be different, values must match).
an example;
SELECT c.CustomerId, c.CustomerName, o.OrderId
FROM Orders AS o
INNER JOIN Customers AS c ON c.CustomerId = o.CustomerId
you can change table and column names as yours, also if you need to see all records included NULL values, may try OUTER JOIN
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
It is such that I have no date in the database, and if it is less than the time / date as we have now so it must go in and refresh the use of the will rank 2. This means that we have, for example. the time is now and if it is not right than he who is in the database so it should not go in and do anything at all.
That means if the date looks like this is it too old.
3/15/2015 09:34:42 AM (it is now.) and 3/15/2015 04:34:42 AM
So it must go into the code to update the user to get rank 2
while (readerBrugere.Read())
{
string brugerid = readerBrugere["id"].ToString();
DateTime brugerdato = Convert.ToDateTime(readerBrugere["trydato"].ToString());
conn1.Close();
if (Convert.ToDateTime(DateTime.Now.ToString("ddmmyyyyHHmmss")) > Convert.ToDateTime(brugerdato))
{
int rankid = 2;
cmd1.CommandText = "UPDATE brugere SET rank = #rank WHERE Id = #brugerid;";
cmd1.Parameters.AddWithValue("#rank", rankid);
cmd1.Parameters.AddWithValue("#brugerid", brugerid);
conn1.Open();
cmd1.ExecuteNonQuery();
conn1.Close();
}
}
It will only run content through if it is to time with me is right than what is in the database
The text of your question hard to decipher, but looking at the code I can suggest a much-improved version:
while (readerBrugere.Read())
{
//if these columns cannot be null, you should be able to use a simple cast
int brugerid = (int)readerBrugere["id"];
DateTime brugerdato = (DateTime)readerBrugere["trydato"];
//don't close your database connection here
//These values are *already* datetimes. There's not need to convert to datetime
// and *especially* no need to convert to strings to compare them
if (DateTime.Now > brugerdato)
{
// the "2" is a constant: just code it into the query that way
string sql = "UPDATE brugere SET rank = 2 WHERE Id = #brugerid;";
//or maybe you wanted this instead:
string sql = "UPDATE brugere SET rank = rank + 1 WHERE Id = #brugerid;";
//AddWithValue() kinda sucks somtimes. I prefer to do it like this instead:
cmd1.Parameters.Add("#brugerid", SqlDbType.Int).Value = brugerid;
//don't use the same connection as you did for the outer query:
using (var cn2 = new SqlConnection(conn1.ConnectionString))
using (var cmd2 = new SqlCommand(sql, cn2))
{
cmd2.ExecuteNonQuery();
}
}
}
Finally, all this is really moot, as I expect you can do this entire process in the database with a single query:
UPDATE brugere
SET rank = rank + 1
WHERE trydato <= current_timestamp AND brugerdi IN
(
...existing query goes here, but only select the brugerdi column ...
)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am writing to develop a program concerning stock of a firm.
I have variable quantity in stock in int, ı am trying to get all quantity and compare with the result written on textbox.
I am using the following code:
SqlConnection sqlcon = new SqlConnection("server=.;database=DB_TEST;trusted_connection=true"); - SERVER CONNECTION
SqlCommand sqlcmd = new SqlCommand("Select SUM(Quantity) from Stock where ProductID='" + cmbxProductID.SelectedValue + "'", sqlcon); - GETTING TOTAL QUANTITY FROM DATABASE - quantity in int
sqlcon.Open(); - SQL CONNECTION OPEN
textBox1.Text = sqlcmd.ExecuteScalar().ToString(); -- transfering total quantity to textbox1
int result=int.Parse(textBox1.Text); -- CONVERT CONTENT OF TEXTBOX to ınt
if (result == 0)
{
MessageBox.Show("Stock is not adequate");
}
sqlcmd.ExecuteNonQuery();
sqlcon.Close()
MessageBox.Show("Stock is OK");
You need to pass the result to a variable & not to textBox1. Then you can compare the variable value & textBox1 value
SqlConnection sqlcon = new SqlConnection("server=.;database=DB_TEST;" +
"trusted_connection=true");
SqlCommand sqlkmt = new SqlCommand("Select SUM(QUANTITY) from Stock " +
"where ProductID='" +
cmbxProductID.SelectedValue + "'", sqlcon);
sqlcon.Open();
int result= sqlkmt.ExecuteScalar();
sqlcon.Close();
if (result == int.Parse(textBox1.Text))
{
MessageBox.Show("Stock in not adeqaute");
}
Mark if this was helpful
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want convert this code into using a DataSet.
I don't have any idea how to retrieve data from a DataSet.
conn.Open();
string strquery = "select * from tblclientinfo where clientId=" +
txtid.Text; SqlCommand sqlcmd = new SqlCommand(strquery, conn);
SqlDataReader sqldreader = sqlcmd.ExecuteReader();
if (sqldreader.HasRows)
{
while (sqldreader.Read())
{
txtid.Text = sqldreader["clientId"].ToString();
txtname.Text = sqldreader["name"].ToString();
txtmobile.Text = sqldreader["mobile"].ToString();
txtcnic.Text = sqldreader["cnic"].ToString();
}
}
else
{
MessageBox.Show("Record for ID" + " " + txtid.Text + " " + "Not Found !");
}
sqldreader.Close();
conn.close();
Do you want something like this ?
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand.CommandText = "select * from tblclientinfo where clientId = #id";
da.SelectCommand.Parameters.AddWithValue("#id", txtid);
da.SelectCommand.Connection = conn;
DataSet ds = new DataSet();
da.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
txtid.Text = row["clientId"].ToString();
txtname.Text = row["name"].ToString();
...
}
The DataReader is the active part reading in the data from the database connection.
The DataSet is a container defined in a generic way so that it may contain any structure of data that tis read in by a DataReader.
You can use this approach:
// Assumes that conn is a valid SqlConnection object.
string strquery = "select * from tblclientinfo where clientId=" + txtid.Text;
SqlDataAdapter adapter = new SqlDataAdapter(strquery , conn);
DataSet resultSet = new DataSet();
resultSet.Fill(resultSet, "resultSet");
//now you can read data from DataTables contained in your dataset and do whatever with it
DataTable FirstTableOfDataSet = resultSet.Tables[0];
As your question asks about the difference, so here it goes:
DataReader is used in connected architecture. That means a connection remains open till you iterate through and fetch all records one by one. Only after fetching records when you write con.Close() it gets closed.
DataSet and DataAdapter are used in disconnected Architecture. That means they bring data and do not have a open connection for a long time. So in case if the database get changed after bringing data you won't have the updates, because it is cached.
Take an example:
An oil company is located at say Dubai(DataSource - Database), it needs to send oil to say USA(Application UI). What are the two ways?
A jet plane carries the oil to USA.- Disconnected. The jet plane is the DataAdapter and the container in which the oil is brought is dataset/datatable.
A pipeline runs through Dubai to USA. - Connected. The pipeline is the reader.
Awkward example. ;) Hope this make the difference little clear.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I want to select id from one table and insert that id to another table.
First I need to read my first table id and want to pass it to string.
Then I need to pass that string to second table.
String selQuery = "SELECT Id FROM MapDataImage WHERE Source='" + TextBox1.Text + "';";
{
int MId = int.TryParse(Id);
String QueryStr = "INSERT INTO User_Images VALUES (#Image)";
SqlCommand scmd = new SqlCommand(QueryStr, conn);
SqlDataReader sqldread = scmd.ExecuteReader();
//String QueryStr = "UPDATE MapDataImage SET Image = #Image WHERE Source='" + TextBox1.Text + "';";
//SqlCommand scmd = new SqlCommand(QueryStr, conn);
scmd.Parameters.Add("#Image", SqlDbType.VarBinary).Value = imgbytes;
scmd.ExecuteNonQuery();
}
so is this correct?
int MId = int.TryParse(Id); //the name id does not exist in current context?
but i want to retrieve particular id value from database
or
int MId = int.TryParse(#Id);
int MId = int.Parse("Id");
Will never work. "Id" is a string literal, it can never be an integer. I think you need to specify a variable
int mId = int.Parse(id);
Aside that, try using TryParse so it's safer.
Also use paramerterised queries on your SELECT statement to prevent SQL Injection.
Please post the rest of your code and I will adjust my answer to accomodate.
You don't create DataReaders objects by yourself. Instead you obtain a reference to DataReader object by invoking ExecuteReader method of Command class.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executereader.aspx