select * only return one value - sql-server

I want select multiple (all) values from table Account.
string query = "SELECT * FROM Account";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader;
connection.Open();
reader = command.ExecuteReader();
reader.Read();
label1.Text = reader["PasswordHash"].ToString();
connection.Close();
Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.
Thanks in advance.

Because you are not looping through the query results, it shows up only one result.
string query = "SELECT * FROM Account";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader;
connection.Open();
reader = command.ExecuteReader();
While(reader.Read())
{
label1.Text += " " +reader["PasswordHash"].ToString();
}
connection.Close();
The above code loops through the query results and will give you what you want in a concatenated string assigned to label1.text. You can also view the results by inserting Console.WriteLine(reader["PasswordHash"].ToString()); in the while loop

You should do
while (reader.Read())
// process information
You need to iterate all the information you retrieved.
Sidenote: Use using statements on your SqlConnection, SqlCommand, and SqlDataReader to make sure the objects get disposed correctly.

The reader only advances one record at a time. You'd need to iterate through the result set in a loop:
while (reader.Read()) {
// do something with the current row by accessing reader[]
}
reader.Close();
There are better ways to structure your code but this illustrates the point you were missing and requires the least changes.

You need to loop, something like this:
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
There is an example in the MSDN docs:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx

The line reader.Read() will get the next row, so you can use while(reader.Read()) to iterate over the rows.

Looking at your code my recommendation is to use some other object to add the code to. Text of a label is not an appropriate choice.
Try using a foreach loop into a list to retrieve all the data that has been returned.

You need a while-loop;
while(reader.Read()) {
Console.WriteLine("{0}", reader[0]);
}

Using where id = 2 and id = 3 would return zero results as as id=2 and id=3 are mutually exclusive. where id = 2 or id = 3 could work.
while (reader.Read()) { /*Do stuff with current row*/ }
could work for iterating through the results

You need to loop and data reader is best way for your code , for sample ,something like this:
SqlDataReader myReader = myCommand.ExecuteReader();
// Always call Read before accessing data.
while (myReader.Read()) {
Console.WriteLine(myReader.GetInt32(0) + ", " + myReader.GetString(1));
}
// always call Close when done reading.
myReader.Close();

Related

How to retrieve values from multiple rows of the same column in SQL Server

I need to search booked patients for the given date. I don"t know what the error in my code is. But I could retrieve only 1 row from the table. Please help
string sp = textBox1.Text;
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = "Data Source=SWATHI-PC\\NM;Initial Catalog=clinic;Persist Security Info=True;User ID=sa;Password=sqlpass";
con1.Open();
string query = "select Booking_dt,Name from patients1 WHERE Booking_dt=#dt ";
SqlCommand cmd = new SqlCommand(query, con1);
cmd.Parameters.Add(new SqlParameter("#dt", sp));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
listView1.Items.Add(dr[1].ToString());
}
I'd say that it's your
if (dr.Read()) { }
block only running once. I don't know the specifics of whichever language you're using, but I'm guessing you need something along the lines of
while (dr.Read())
{
listView1.Items.Add(dr[1].ToString());
}
which should iterate through dr.

How to read Data from Dynamically added TextBoxes to a FlowLayoutPanel?

I have added textboxes dynamically in a FlowlayoutPanel from SQL table like this
string query = "SELECT* FROM tblA";
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=DummyData;Integrated Security=True"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(query, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Label objLbl = new Label();
TextBox objText = new TextBox();
objLbl.Text = reader["A_Name"].ToString();
objText.Name = "txt"+reader["ID"].ToString();
pnlFlow.Controls.Add(objLbl);
pnlFlow.Controls.Add(objText);
}
}
}
It's working fine. Now the problem that I'm facing is when user enters some data in these textboxes. How do I get that data for further processing?
There are a number of ways you could do this, depends on how and when you need to get the values.
If you need to read them all at once, something like:
foreach(Control c in pnlFlow.Controls)
{
if c.Name.StartsWith("txt")
// process the text box
// you might want to use a more distinct naming pattern to be safe
...
}
If you need to process them individually and at different times, you could reference them by name in the Controls collection:
string textBoxName = "txt12345";
string valueText = ((TextBox)pnlFlow.Controls[textBoxName]).Text;
Of course both snippets need better error handling, but I'll leave that to you.

How to update multiple rows / How to perform Operation on multiple records (C#, SQL Server)

I have a database table name Players (ID, Name, Scores).
here is my code to binding it with database
private void playerList(int team1_ID)
{
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
string query = "SELECT player_name AS [Player Name] , Score AS [Score] FROM Players WHERE Team_id= " + team1_ID;
SqlCommand cmd = new SqlCommand(query, con);
adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds, "Players");
dGridPlayers.DataSource = ds.Tables["Players"];
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
This code is working fine. It returns a list of 11 players and their Scores.
Now I want to perform some arithmetic operation on Score of each player and want to store back (update ) to the database table. Please tell how to do this.
(I don't want to hit SQL every time to update for each player's score. I want to update every players scores in one go after finishing the operations.)
You need to define
an UPDATE SQL statement to do your update
call that UPDATE from your C# code
use parametrized query to avoid SQL injection and bad performance !!
put your usage of SqlConnection and SqlCommand into using() {....} blocks to ensure proper disposal
Something like this:
// define your UPDATE query
string updateQuery = "UPDATE dbo.Players SET Score = Score + #Value WHERE Team_id = #TeamID";
// two nested "using" blocks for conenction and command
using (SqlConnection conn = new SqlConnection(.....))
using (SqlCommand cmd = new SqlCommand(updateQuery, con))
{
// define the parameters and provide values
cmd.Parameters.Add("#Value", SqlDbType.Int).Value = someValue;
cmd.Parameters.Add("#TeamID", SqlDbType.Int).Value = teamID;
// open connection, execute the UPDATE, close connection
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
To update records just apply something similar to what marc_s suggested.
If you want to update all records at once keep primary keys and new values in a structure like this
Dictionary<int, int> values = new Dictionary<int, int>();
Key for the dictionary will hold the primary key for the table and value will be the new score for that record.
When you want to update the database just loop through all of these inside of the using SQLCommand block marc_s showed
using (SqlCommand cmd = new SqlCommand(updateQuery, con))
{
// open connection, execute the UPDATE, close connection
conn.Open();
foreach (KeyValuePair<int, int> row in values)
{
cmd.Parameters.Clear();
cmd.Parameters.Add("#PK", SqlDbType.Int).Value = row.Key;
cmd.Parameters.Add("#Score", SqlDbType.Int).Value = row.Value;
cmd.ExecuteNonQuery();
}
conn.Close();
}

Inserting a single row with large number of columns in SQL Server

I have a huge form that has around 110 fields columns (single row) that need to be saved in a database.
What is the best approach to insert these many columns into the database using ADO.NET?
I don't think I should be using an insert statement like this, since the query would be very large due to the number of fields.
conn.Open();
string insertString = #"
insert into Categories (CategoryName, Description)
values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.ExecuteNonQuery();
I think of dumping the data into temp file and then adding them into a datatable and then inserting them into database using SqlBulkCopy.
Is there a better approach? How would you handle this situation?
I am afraid there isn't a good shortcut for inserting this number of columns, but using parameters will likely save some debugging time. By using parameters you do not need to worry about things likes apostrophes in strings and type conversions. Here's a sample:
public static void TryThis()
{
try
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = "YourConnectionString";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Categories (CategoryName, Description) VALUES (#CategoryName, #Description)";
cmd.Parameters.AddWithValue("CategoryName", "Miscellaneous");
cmd.Parameters.AddWithValue("Description", "Whatever doesn't fit elsewhere");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

Help with using SQL select statement in C#

I am trying to retrieve some rows from the database using simple SELECT statement in SQL and displaying them in a Data Grid, Now what I have to do is to multiply the retrieved values with some factor and then display it. I am trying to achieve it the following way:
I have declared PerDoseSize1 as a double variable which gets its value from a function. I am not able to do it this way.
It gives me an error saying "PerDoseSize1 is not a valid column"
public void FillDG1(string Chemical_Name0, string Chemical_Name1, string Chemical_Name2, string Chemical_Name3,double PerDoseSize1)
{
objDs.Clear();
string connString ="Data Source=dk1;Integrated Security=True";
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT [Chemical Name],([GWP])*(perdosesize) AS GlobalWarming, ([ODP])*(perdosesize) AS OzoneDepletion, [WDP] AS WaterDepletion ,[FDP] AS FossilDepletion FROM [Surfactants$] WHERE ([Chemical Name] IN ( #ChemicalName0, #ChemicalName1,#ChemicalName2 ,#ChemicalName3)) ";
cmd.Parameters.AddWithValue("#ChemicalName0",Chemical_Name0);
cmd.Parameters.AddWithValue("#ChemicalName1", Chemical_Name1);
cmd.Parameters.AddWithValue("#ChemicalName2", Chemical_Name2);
cmd.Parameters.AddWithValue("#ChemicalName3", Chemical_Name3);
cmd.Parameters.AddWithValue("#perdosesize", PerDoseSize1);
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
dAdapter.Fill(objDs);
DataTable myDataTable = objDs.Tables[0];
DG1.DataContext = objDs.Tables[0].DefaultView;
cmd.ExecuteNonQuery();
MessageBox.Show(ChemicalName0,ChemicalName1);
con.Close();
}
It still doesn't seem to work, Is it still wrong? Please help!
The way you have written it:
"SELECT ([GWP])*(PerDoseSize1) AS GlobalWarming, ([ODP])*(PerDoseSize1)
Will not work because the function argument you're passing in won't be substituted in your SQL.
So you can try creating a Parameter argument for PerDoseSize1 and pass it into the SQL, like you're doing with AddWithValue.
I have declared PerDoseSize1 as a
double variable which gets its value
from a function
So what? How does that get into the SQL? So far there is NOTHING saying this. YOU have to put it into the SQL and assign it to a parameter. It wont magically hook up.

Resources