Returning an integer value from SQL Server - c#

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);

Related

reading data with OleDbDataReader

I'm trying to get the value of a Field (User Access level it's 1 or 2 in string format) after login
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dsms.accdb");
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT AL From Users WHERE Username='" + textusername.text + "'", connection);
reader = command.ExecuteReader();
if( reader.HasRows)
{
MessageBox.Show("success","status");
label1.Text = reader.GetString(1);
}
else
MessageBox.Show("failur", "status");
connection.Close();
I did execute the code in Access and it's was totally fine
but in the program, it says "No data exist for the row/column"
The main problem in your code is the fact that you need to call reader.Read() to get anything out from a DataReader. Just calling HasRows doesn't position the reader on the first record of your query.
There are other problems in your code.
Disposable objects like connections, commands and readers should be created in a using statement to ensure proper disposition after use and because you have only one field in your query, you should use the index 0 to retrieve it not 1.
Finally the most important one. You should NEVER concatenate strings to build an sql query. In this way a malicious user could write anything in your textbox, even valid sql commands that could be executed against your database. It is called Sql Injection and if you search for these terms you will find very detailed discussions about it. However, to avoid this problem (and others like parsing input with apostrophes) you use a parameterized query like below.
using(OleDbConnection connection = new OleDbConnection(.....))
using(OleDbCommand command = new OleDbCommand("SELECT AL From Users WHERE Username=#name", connection);
{
connection.Open();
command.Parameters.Add("#name", OleDbType.VarWChar).Value = txtusername.text;
using(OleDbDataReader reader = command.ExecuteReader())
{
if( reader.Read())
{
MessageBox.Show("success","status");
label1.Text = reader.GetString(0);
}
else
MessageBox.Show("failur", "status");
}
}

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.

MySqlCommand in Asp.net WEB Forms to Display in Label

i have this sql command
string myreg = "select registration_no from truck where truck_id ='" + truckID + "'";
MySqlCommand cmd = new MySqlCommand(myreg, conn);
i want to put the value of myreg to my RegistrationNo.Text label.
i have this RegistrationNo.Text = myreg; and it displays select registration_no from truck where truck_id on my page
You need to read something about the workings of ADO.NET and its providers.
To get the result of that query in your textbox you need
Open a connection to your MySql Server
Prepare a command to send to the Server
Get back the result
Write the result to your textbox
All these passages requires the use of specific classes and some code to glue everything together
// Prepare your command using a parameter placeholder
string myreg = "select registration_no from truck where truck_id =#id";
// Build the connection to the server and build the command to execute
using (MySqlConnection cnn = new MySqlConnection(.... the connection string that identifies your server and db ))
using (MySqlCommand cmd = new MySqlCommand(myreg, cnn))
{
// Open the connection
cnn.Open();
// Add the parameter expected
cmd.Parameters.Add("#id", MySqlDbType.VarChar).Value = truckID;
// Execute the command and get back the return value (if found)
object result = cmd.ExecuteScalar();
// Check if the ExecuteScalar has returned something
if(result != null)
RegistrationNo.Text = result.ToString();
else
... message to your user about the failed search ...
}
PS. I have assumed that your variable truckID is a string because in your original code you have passed it between single quotes, but if it is an integer then you need to modify the parameter type to MySqlDbType.Int32
Also, I have used the ExecuteScalar method instead of ExecuteReader because I think that your query returns just a row with a single column and for this task it is better to use ExecuteScalar
You can use datareader also.See MSDN documentation here.
using (connection)
{
SqlCommand command = new SqlCommand(
"SQL Query",
connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}

to find max value from a given table in sql express

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;

How do get a simple string from a database

The following code does not work. There is only 1 row in this table. How do I just get the statement that the sql would return?:
SqlConnection conn = new SqlConnection(connectionStringArg);
SqlCommand command = new SqlCommand("select applicationname from tbl_settings");
command.Connection = conn;
conn.Open();
string simpleValue = command.ExecuteReader()[0].ToString();
conn.Close();
return simpleValue;
Okay any help on how to achieve this relatively simple task would be great.
Since there's only a single value returned, you could do this:
string value = (string)command.ExecuteScalar();
If you need more than the first column from the first row returned, you'll need to use ExecuteReader(). See driis' answer.
The DataReader can't be indexed like that. You need something like:
using(conn)
using(var reader = command.ExecuteReader())
{
reader.Read();
string simpleValue = reader.GetString(0);
}
The general idea is to advance the reader for each record (using Read), then you can read values from the row. As pointed out in another answer, if you know there is only one single value in the result set, command.ExecuteScalar() gives you just that.
You have to call the Read method on a DataReader returned from ExecuteReader to get to the first row. Something like this:
SqlDataReader rdr = command.ExecuteReader();
if (rdr.Read())
...
You'd do e.g.
using(SqlConnection conn = new SqlConnection(connectionStringArg))
using(SqlCommand command = new SqlCommand("select applicationname from tbl_settings")) {
command.Connection = conn;
conn.Open();
SqlDataReader reader = command.ExecuteReader();
if(reader.read()) {
return reader.GetString(0);
}
return null;
}
For a single string you want to use ExecuteScalar to get a single value and then attempt to cast it to string.
From doc: Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
Example:
string result = command.ExecuteScalar() as string;
For small stuff I often find LINQ2SQL the easiest to set up and use. This tutorial should get you up and running in a few minutes. For bigger projects LINQ2SQL is considered obsolete, see this question for discussion and alternatives.
Check DataReader.Read() you need to call it.
string applicationname = "";
using(var reader = command.ExecuteReader())
{
reader.Read();
applicationname = reader.GetString(reader.GetOrdinal("applicationname"));
}
var query_result = com.ExecuteScalar() as string;
if (!string.IsNullOrEmpty(query_result )) // do your thing here...

Categories

Resources