Problem while printing a maximum value obtained from the database - c#

I am trying to find the MAX number from a database field,The query below returns me the maximum value if i run it in SQL Enterprise Manager but i am not able to print the value in numbwe. Please help me to print the MAX value obtained from the database.
SqlConnection MyConnection = new SqlConnection("Data Source=localhost;Initial Catalog=hcgoa;User Id=sa;Password=;");
SqlCommand MyCmd = new SqlCommand("SELECT MAX([no]) AS Expr1 FROM jmain", MyConnection);
MyConnection.Open();
SqlDataReader myReader = MyCmd.ExecuteReader();
if (myReader.Read())
{
string numbwe = myReader["no"].ToString();
Response.Write("Max no. is : " + numbwe);
}

You need to use Expr1 as the key, not no.
That's because you're doing:
SqlCommand MyCmd = new SqlCommand("SELECT MAX([no]) AS Expr1 ...
(note the AS clause) so the column is named Expr1. Hence:
string numbwe = myReader["Expr1"].ToString();
should do it.
Although, in fairness to those who come after you, Expr1 is not a very descriptive identifier. Consider the possibility of changing it to something like MaxNum (both in the select and the key, of course).

You should look at the ExecuteScalar() instead if you are going to return a single value.
MSDN: Use the ExecuteScalar method to
retrieve a single value (for example,
an aggregate value) from a database.
This requires less code than using the
ExecuteReader method, and then
performing the operations that you
need to generate the single value
using the data returned by a
SqlDataReader.

You're trying to print the value of a column that doesn't exist in the query result. Your query returns a column named Expr1, not a column named "no"
Change
string numbwe = myReader["no"].ToString();
to
string numbwe = myReader["Expr1"].ToString();

should be string numbwe = myReader["Expr1"].ToString();
as you are specifying your column name in sql statement Expr1
SELECT MAX([no]) AS Expr1

Related

How to use value from SQL Server in C#

I got value from SQL Server using this C# code:
SqlDataReader reader = new SqlCommand("select Top 1 Client From _ClientName group by Client order by count(*) desc", sqlCon.ShardDB).ExecuteReader();
How can I use this value again to insert it into another table?
Just use name of the column begin returned from the database i.e "Client" here. If it is a string, you can use .ToString(). If it is another type, you need to convert it using System.Convert
string Value = reader["Client"].ToString();
First, for readability sake, try separating your code into separate lines, like so:
SQLReader reader;
SQLCommand SQLCmd = new SQLCommand();
SQLCmd.CommandText = "select Top 1 Client From _ClientName group by Client order by count(*) desc";
SQLCmd.Connection = sqlCon.SharedDB;
reader.Execute(SQLCmd);
If I understood your comment to Sajeetharan's previous answer, you want to know how to advance to the next result if your query returns more than one. Have you tried SQLReader.Read()?
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx

Database Handling in C#

I'm having some problems on my application since I'm not very experienced on the database handling, so far I've created my database with a table, and what I wanted to do is to show a specific data from the table as a variable.
My application has to do with chemical elements, therefore the table "elements" has all of them. I was thinking of making a random element generator using a random number to get any of the elements in the table with a query or something.
Random ra = new Random();
int random_anumber = ra.Next(1, 9);
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Francisco\Documents\FormData.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM elements", con);
I was thinking on putting the random_anumber instead of the "*" but it's still not showing a single element. Since I don't know how to show them of convert the data into a variable.
The "*" in the SQL statement is a field name selector and not a filter. So changing the * to something else won't limit your query to a single element. You have to add a where clause for that.
To solve this you can either use the SqlDataAdapter onto a DataSet and use the DataTable within the DataSet to grab a random row by using the random number as the index or run a simple query. I recommend running a query if all you need to do with this data is display a random element.
--- Update ---
MS SQL Server Statement:
SELECT TOP 1 * FROM table
ORDER BY NEWID()
MySQL Statement:
SELECT * FROM table
ORDER BY RAND()
LIMIT 1
The * is a wildcard character that select all columns/fields of the table. You can change the to a comma delimited list of columns/fields you want to retrieve from the database.
Hope that the Table elements having a unique Key Field(let it be element_id) then you can access the Random Element by Specifying the ID in the Where Clause, Then your Query will be like The following:
string querySQL="SELECT * FROM elements Where element_id=#id";
SqlCommand cmd = new SqlCommand(querySQL, con) // con is the Connection
cmd.Parameters.AddWithValue("#id", random_anumber);
// Get data using Adapter
This is how I do it everyday:
Note: Here you can see that I use Sqlite in my example. You can use SQL by removing the Lites and using the right classes in SQL respectively.
string ConnectionString = "data source={0}; initial catalog={1}; integrated security=true; application name= <Your App Name>" providerName="System.Data.SqlClient";
string DatabasePath = "<Your Path to your database>";
string commandstring = "SELECT * FROM elements";
using (SQLiteCommand MyCommand = new SQLiteCommand(commandstring, Connection))
{
using (SQLiteDataReader MyReader = MyCommand.ExecuteReader())
{
while (MyReader.Read())
{
// Here is your result:
// You can do anything that you want with it.
// The 0 shows the first column. If your result returns more than one column, //you can use other numbers like 1,2..n to get other columns out of your data //reader.
MyReader.GetString(0);
}
}
}`

C# Select Query Failed with no errors

I'm having trouble with a simple SELECT query, I cannot see why it isn't working.
Here is the code:
conn.Open();
string GetPayrollQuery = "SELECT PayrollNo FROM [Employee] WHERE (FirstName + ' ' + LastName) = #Name";
OleDbCommand GetPayroll = new OleDbCommand(GetPayrollQuery, conn);
GetPayroll.Parameters.AddWithValue("#Name", OleDbType.VarChar).Value = cbbEmployees.Text;
var GotPayroll = GetPayroll.ExecuteNonQuery();
MessageBox.Show(GotPayroll.ToString());
return Convert.ToInt32(GotPayroll);
The code runs fine however it isn't extracting the data. Can anyone see why this would be?
I bet #name is coming as "MikeSmith" instead of "Mike Smith".
3 things:
try to open SQL profiler and check what you are executing on database
check database collation, is it case sensitive?
remove executenonquery (it's must used with update, delete, not select) and try executescalar (if one result for one row is exptected, otherwise try to fill a datatable or use datareader)
Make sure the same query runs in SQL using those parameter values.
Change GetPayroll.ExecuteNonQuery() to GetPayroll.ExecuteScalar() so to return a single result.
Change GetPayroll.Parameters.AddWithValue("#Name", OleDbType.VarChar).Value = cbbEmployees.Text; to GetPayroll.Parameters.AddWithValue("#Name", cbbEmployees.Text);
Use cbbEmployees.SelectedText. Fixes the problem.

Getting "Invalid Column Name " Sql Exception in the following code

I am trying to pass both Column name and the Value to be checked in the code at runtime. However I am getting an "Invalid Column Name " exception.
The code is as follows :
string temp = TextBox1.Text.ToString();
SqlConnection con = new SqlConnection("data source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Sagar\\Documents\\Test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand com = new SqlCommand("Select * from Employee Where #field = Sagar", con);
com.Parameters.AddWithValue("#field", DropDownList1.SelectedValue.ToString());
//com.Parameters.AddWithValue("#value", temp);
SqlDataAdapter da = new SqlDataAdapter(com);
con.Open();
SqlDataReader reader = com.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
The message says that there is no column named 'Sagar' in the table. Is there such a column? Things would be easier if you showed us the table schema instead of having us guess from the error message.
It is not possible to parameterize column names using SqlParameter in C#. This has been discussed here multiple times.
What's happening with the query the way Vidhya Sagar Reddy is doing it, is the following. He assumes that the following query
Select * from Employee Where #field = 'Sagar'
is replaced by this query when setting "Name" as the value for the #field parameter:
Select * from Employee Where Name = 'Sagar'
This, however, is wrong! What's happening is that the #field parameter is replaced as follows:
Select * from Employee Where 'Name' = 'Sagar'
This returns no results, as the WHERE clause is always false. Of course, if you use the field name Sagar, this akways returns true, as the statement then reads:
Select * from Employee Where 'Sagar' = 'Sagar'
Here's an easy test to prove what I've said above. Use the following statement to set the #field parameter (supposed, there's no column named eirghoerihgoh in the table):
com.Parameters.AddWithValue("#field", "eirghoerihgoh");
If the query executes correctly (maybe not returning any results), the above is correct. If it was not correct, an exception should be thrown about the eirghoerihgoh column not being present.
Thank you Vidhya Sagar Reddy for proving my point. By using this line
com.Parameters.AddWithValue("#field", "eirghoerihgoh");
you say you didn't get any results, but you also didn't get an exception. However, if the statement really had been changed to
Select * from Employee Where eirghoerihgoh = 'Sagar'
there had to be an exception saying that there was no column named eirghoerihgoh. As you didn't get that exception, there's only one possible explanation: The statement was changed to
Select * from Employee Where 'eirghoerihgoh' = 'Sagar'
and this executes, but doesn't return results, as the condition is always false.
Instead you can make your code this way, which works perfectly:
"Select * from Employee Where "+DropDownList1.SelectedValue.ToString()+" =
'Sagar'" – Vidhya Sagar Reddy
The reason for that is quite simple, the value that are to be specified in SQL should be in single quotes and this is a simple mistake by the way..!!!!
SqlCommand com = new SqlCommand("Select * from Employee Where #field = 'Sagar'", con);
And even change the parameter to "field" in the following line and not "#field"..!!
com.Parameters.AddWithValue("field", DropDownList1.SelectedValue.ToString());
This is working..>!!!!

Read single value from query result

I am trying to return the result that I found in my query to the ASP.net table. How do I do that? I already have the query, I am just having trouble getting the count result back.
string configMan.ConnString["connect"].ToString();
iDB2Conn temp = new iDB2Conn
string query = "select Count(*) as total from test";
...
this is where I am having trouble.
This is where the SqlCommand object comes in handy.
int result = 0;
using(SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand sql = new SqlCommand("SELECT COUNT(*) FROM test", conn);
result = (int)sql.ExecuteScalar();
}
In ADO.Net, the simplest way is to use the ExecuteScalar() method on your command which returns a single result. You don't explicitly list what database or connection method you are using, but I would expect that most database access methods have something equivalent to ExecuteScalar().
Try using the ExecuteScalar method on your command. You should be able to use the generic one or cast the result to an int/long.

Categories