to find max value from a given table in sql express - c#

i am trying to retrieve latest data from my database table.
i am using max(columnName) but not having result to my liking.
i keep getting column name instead of any value
please help me out in this...
the code for retrieving max value is like this
dbConnection dbCon = new dbConnection();
con = dbCon.doConnection();
SqlCommand cmd = new SqlCommand();
String query = "select max(studentNo) from studentInfo;";
cmd.Connection = con;
cmd.CommandText = query;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
String x=reader["studentNo"].ToString();
}
here the studentNo is the column name whose value i need to extract and it is of int type
while printing the string x on my application i get studentNo instead of the value.
now i am short of clue to solve the prob because i can't find anything wrong with the code.
do help me in this one

The problem is in the way you are accessing the value, you can change two things here. Either access the reader by index or name the column appropriately in the query.
select max(studentNo) as StudentNo from studentInfo;

Your query outputs one row and one column of data, so you might consider using ExecuteScalar() instead of ExecuteReader():
dbConnection dbCon = new dbConnection();
con = dbCon.doConnection();
SqlCommand cmd = new SqlCommand();
String query = "select max(studentNo) from studentInfo;";
cmd.Connection = con;
cmd.CommandText = query;
String x = cmd.ExecuteScalar().ToString();

You need to give alias to your select after applying aggregate function
i.e. select max(studentNo) as NO from studentInfo
and while reading it
String x=reader["NO"].ToString();

First you need to set the correct alias do the column:
select max(studentNo) as 'studentNo' from studentInfo;
And second, you may want to assign a database to the table:
select max(studentNo) as studentNo from databaseName..studentInfo;

Related

Need to select a value from table and store it into variable

Hello everyone I am currently working on some testing project and I am having a little problem. Using selenium, I need to SendKey in specific element but instead of fixed value i need to use value (data) from my database. Can anyone help me with how to retrieve single value from database and store it in a variable so i can use it later.
Thank you and sorry for a noobish question - see code below:
SqlConnection conn = new SqlConnection();
SqlCommand command;
SqlDataReader dataReader;
conn.ConnectionString = "Server=******;Database=****;User ID=sqlserver;password=****;MultipleActiveResultSets=true;");
string query = "select RequestID, from AutomaticPayment where RequestID ='1230322'";
DataTable dt = new DataTable();
command = new SqlCommand(query, conn);
conn.Open();
dataReader = command.ExecuteReader();
dt.Load(dataReader);
driver.FindElement(By.Id("requestID")).SendKeys(VALUE FROM DATABASE);
You can use the following code
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlDataAdapter sda = new SqlDataAdapter(query, connection);
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
try
{
result = cmd.ExecuteScalar().ToString();
}
catch(NullReferenceException n)
{
result = "";
}
}
ExecuteScaler gets you the first column of the first row and additional columns are ignored. Use the value from result in your SendKeys()
Use conditions to limit the result:
Select data
SELECT TOP 1 RequestID FROM AutomaticPayment // Always returns 1 row
Or
SELECT RequestID FROM AutomaticPayment WHERE Id = 123 // Id must be unique to return 1 row
And maybe other ways.
Get value
var value = dt.Rows[0][1];
Or
var value = dt.Rows[0]["RequestID"];
From what i worked on with SqlCommand just do the following :
int yourId = 0;
dataReader = command.ExecuteReader()
while(dataReader.Read())
{
yourId = dataReader.GetInt32(0);
}
With that, you should have your value set to the first column of the dataReader. (that is selected thanks to your query, since you are requesting on a specific id, i guess it will return only one column
there is many other type available for Reader : Reader Microsoft Doc
And if you have in the futur many data to collect, use the ORM entity framework, work well for me
Source
EDIT :
Since you are only querying one data, maybe the solution of #work_ishaan is better than mine in this case, check it out.

Sql Conversion from nVarchar to int error

Error:
Conversion failed when converting the nvarchar value 'select TopicID from Topic where TopicName='Data Structure'' to data type int
Code:
public void BindGridview()
{
string strConnString = ConfigurationManager.ConnectionStrings["infoConnectionString"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(strConnString);
sqlcon.Open();
string strquery2 = "select TopicID from Topic where TopicName='" + ddltopic.SelectedItem.Text+ "'";
string strquery3 = "select i.name ,i.score from info as i,Topic as t where i.topic_id=#topicid";
SqlCommand cmd = new SqlCommand(strquery3,sqlcon);
cmd.Parameters.AddWithValue("#topicid",strquery2);
cmd.Connection = sqlcon;
SqlDataReader dr;;
this.GridView1.DataSource =cmd.ExecuteReader();
this.GridView1.DataBind();
sqlcon.Close();
}
}
Could anyone tell me where I am going wrong? Any help would be appreciated.. Please reply as soon as possible.. Thanks in advance..
You are passing the in the entire query not the topic id in this line here
cmd.Parameters.AddWithValue("#topicid",strquery2);
It is then taking that as a parameter and adding it to the following query. If this is a subquery, you can always execute it first and then use the result in the paramter.
But the reason that it is failing is because you are essentially trying to compare a String to an int by passing in the query string like that.
I think what you want in cmd.Parameters.AddWithValue("#topicid",strquery2); is the value returned by strquery2???? , the topic id will get generated if you execute this query first and the result of this will be used instead of query itself
Is that what you want ??
can you tried with below code, I have not tested but its should work for you
public void BindGridview()
{
string strConnString = ConfigurationManager.ConnectionStrings["infoConnectionString"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(strConnString);
sqlcon.Open();
//Equal is not working when subquery return more records
string strquery2 = "select i.name ,i.score from info as i,Topic as t where i.topic_id in (select TopicID from Topic where TopicName=#TopicName)";
SqlCommand cmd = new SqlCommand(strquery2, sqlcon);
cmd.Parameters.AddWithValue("#TopicName", ddltopic.SelectedItem.Text);
cmd.Connection = sqlcon;
SqlDataReader dr; ;
this.GridView1.DataSource =cmd.ExecuteReader();
this.GridView1.DataBind();
sqlcon.Close();
}
Not an actual answer, but comments are too short for this.
This code is vulnerable to SQL injection:
string strquery2 = "select TopicID from Topic where TopicName='" + ddltopic.SelectedItem.Text+ "'";
Imagine that at some point in the future someone (you or someone else who is modifying your code) decides to replace the drop-down list with a combo box? Now imagine someone enters this text into the combo box:
'; TRUNCATE TABLE Topic; --'
Now your SQL server is going to do this:
select TopicID from Topic where TopicName = '';
TRUNCATE TABLE Topic; --'
Learn to use parameters.

Is this query to retrieve data from database correct?

I need to retrieve a value from a field in database. I have the used following code. but the value checkOrderId (which I need) shows the SQL string instead of the value from database. I don't know why it is doing so. Could somebody help me please?
string connectionString = "Data Source = xxyyzz;Initial Catalog = xyz; Integrated Security = True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From" + tableName + "ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
//cmd.ExecuteNonQuery();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == checkOrderId)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
I am new and dont have reputation to answer my question immediately. With everybody's help, i got this one solved...Great help, thanx everybody...following is my code.
string connectionString = "Data Source = EAEDEV;Initial Catalog = GIS; Integrated Security = True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
string valueReturned = (string)cmd.ExecuteScalar();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == valueReturned)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
}
You need to execute the query and check the results, here you are just comparing a string with the query SQL.
Please see here
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson03
for a tutorial.
Your expectation of the result being set into checkOrderId is incorrect. In this instance checkOrderId is just the query to execute and not the actual result.
You need to read the value back from executing the command:
using (var connection = new SqlConnection(connectionString))
using (var comm = new SqlCommand("Select TOP 1 OrderID From [GIS].[SecondaryTraffic].[PotentialBackHauls] ORDER BY InsertDate DESC", connection))
{
connection.Open();
object result = comm.ExecuteScalar(); // This is the key bit you were missing.
if (result != null)
{
// You can cast result to something useful
int orderId = (int)result;
}
} // Both comm and connection will have Dispose called on them here, no need to Close manually.
ExecuteScalar returns the value in the first cell (ie, column 1 row 1) as an object that you can cast to a better type (depending on what type it was in the result-set schema).
If you need to read multiple values, you need to look at ExecuteReader.
There are also other ways of doing this using output parameters, but that would pollute the point of the answer.
You can add space to your query
"Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
Nota : I suggest you to use AddWithValue method with your parameter
string checkOrderId = "Select TOP 1 OrderID From #tableName ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
cmd.Parameters.AddWithValue("#tableName", tableName );
Link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx
You don't actually run your command anywhere. Instead of the commented-out cmd.ExecuteNonQuery, you should look into the ExecuteScalar method, which allows you to read back a single result value from a query - which is what your query returns.
Add
int i = (Int32) cmd.ExecuteScalar();
right after
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
then the variable i will contain the order id
No, this is not correct. You are comparing the variable orderId to your query string. I doubt that's what you want to do. I imagine you'd be better off calling cmd.ExecuteScalar() to retrieve the actual OrderID value. As noted by other answers, your query string is missing a space. But most importantly, it is bad practice to construct SQL queries in code. Although I can't see a security issue with this code, if you continue to use this method you will probably write code that is vulnerable to SQL injection. I recommend you learn to either use parameters or LINQ to build your queries.

Returning an integer value from SQL Server

I have an SQL query as follows:
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT id FROM Pages WHERE pageName=about",conn);
//cmd.Parameters.Add("#pageName","hakkinda");
SqlDataReader reader = cmd.ExecuteReader();
flID = reader.GetInt16(0);
reader.Close();
conn.Close();
I get an error message:
Invalid attempt to read when no data is present.
What's wrong?
I notice a couple potential issues:
You need to call reader.Read(), before trying to read data from it. This is usually done in a loop when people expect multiple rows.
while (reader.Read()) {
flID = reader.GetInt16(0);
}
also in your SQL if "about" is meant to be a literal and not another column name you probably need single quotes around it:
"SELECT id FROM Pages WHERE pageName='about'"
Your query is returning 0 results. This is because the parameter value in the SQL string is missing quotes. It should read as follows (notice the single quotes around the word 'about'):
SqlCommand cmd = new SqlCommand("SELECT id FROM Pages WHERE pageName='about'",conn);
You have to call DataReader.Read to fetch the result:
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
DataReader.Read returns a boolean, so if you have more than 1 result, you can do:
while (reader.Read()) {
// read data here
}
Your select statement should be:
"SELECT id FROM Pages WHERE pageName='about'"
If you expect only single value to be returned, you can use .ExecuteScalar()
flID = int.Parse(query.ExecuteScalar().ToString());
Also, use single quotation marks for pageName value.
SqlCommand cmd = new SqlCommand("SELECT id FROM Pages WHERE pageName='about';",conn);

SQL Server and C#: get last inserted id

public static void CreateSocialGroup(string FBUID)
{
string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (#FBUID); SELECT ##IDENTITY AS LastID";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#FBUID", FBUID);
connection.Open();
command.ExecuteNonQuery();
}
}
Is this the right way to do it? And how do i get LastID in to a variable? Thanks
OUTPUT clause?
string query = "INSERT INTO SocialGroup (created_by_fbuid)
OUTPUT INSERTED.IDCol --use real column here
VALUES (#FBUID)";
...
int lastId = (int)command.ExecuteScalar();
You can use ExecuteScalar to get the last value from a Sqlcommand.
The scope_identity() function is safer than ##identity.
If your server supports the OUTPUT clause you could try it with this one:
public static void CreateSocialGroup(string FBUID)
{
string query = "INSERT INTO SocialGroup (created_by_fbuid) OUTPUT INSERTED.IDENTITYCOL VALUES (#FBUID)";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#FBUID", FBUID);
connection.Open();
var _id = command.ExecuteScalar();
}
}
Personally, I would re-write your code to use Parameters. You could either use an InputOutput parameter or an Output Parameter. However, using a Return Value in your SQL would also work.
Full examples on this can be found on MSDN.
I would also use Scope_Identity() rather than ##Identity this will ensure that you will reveice the ID that relates to the current transaction. Details on Scope_Identity can be found here.
U can try ExecuteScalar for getting the LastID value.
I'd recommend to use a stored procedure to do this. You can give it an OUTPUT parameter which you can use to return the id value back to your app.
cmd = new SqlCommand("Insert into table values (1,2,3); SELECT SCOPE_IDENTITY()", conn);
lastRecord = cmd.ExecuteScalar().ToString();
Use Stored Procedure only for the queries and use SCOPE_IDENTITY to get max value.
SqlCommand command = new SqlCommand("select max(id) from SocialGroup ", connection);
int lastId = (int)command.ExecuteScalar();

Categories

Resources