Select sql how to get value DataReader - c#

I want to retrieve value /miejsca/, but I don't how it works. For example please show me how selecting value define as variable or how to show it in textbox.
At this point I recieve "System.Data.SqlClient.SqlDataReader" in textbox.
SqlDataReader reader;
cn.Open();
cmd.CommandText = ("SELECT miejsca FROM oferty WHERE oferty.idoferty = #rezerw");
cmd.Parameters.AddWithValue("#rezerw", rezerw);
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
reader = cmd.ExecuteReader().Read
string rs = Convert.ToString(reader);
TextBox1.Text = rs;//at this point i recieve "System.Data.SqlClient.SqlDataReader" in textbox
cn.Close();

If you are reading a single row and a single column: just use ExecuteScalar():
string rs = (string)cmd.ExecuteScalar();
But to answer your question, the normal usage is:
using(var reader = cmd.ExecuteReader())
{
while(reader.Read())
{
// read a row, for example:
string foo = reader.GetString(0);
Console.WriteLine(foo);
}
}

Related

C# Query MS-Access Table and place read values from column in a text box

Below is a snapshot of my code. I am trying to access the only column in the customer table and place the values into a textbox on the form. I keep getting the error with my code "InvalidOperationException was unhandled" at the line declaring dr as a OleDbDataReader object.
What do I have wrong with the below code that would be giving me this error?
Should I do a list to pick out the text I want from the database?
How can I return the column values from access into a list in C# so that I can search the list for a particular value?
string strsql = "Select * from Customer";
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = strsql;
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
textBox1.Text += dr["Customer"].ToString();
}
conn.Close();
A command carries the info to be executed, a connection carries the info to reach the database server. The two objects should be linked together to produce any result. You miss that line
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = strsql;
cmd.Connection = conn; // <= here
conn.Open();
Remember also that disposable objects like a command, a reader and a connection should be disposed immediately after usage. For this pattern exists the using statement
So you should write
string cmdText = "Select * from Customer";
using(OleDbConnection conn = new OleDbConnection(.....constring...))
using(OleDbCommand cmd = new OleDbCommand(cmdText, conn))
{
conn.Open();
using(OleDbDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
.....
}
}
Here is some sample code.
try
{
using (OleDbConnection myConnection = new OleDbConnection())//make use of the using statement
{
myConnection.ConnectionString = myConnectionString;
myConnection.Open();//Open your connection
OleDbCommand cmdNotReturned = myConnection.CreateCommand();//Create a command
cmdNotReturned.CommandText = "someQuery";
OleDbDataReader readerNotReturned = cmdNotReturned.ExecuteReader(CommandBehavior.CloseConnection);
// close conn after complete
// Load the result into a DataTable
if (readerNotReturned != null) someDataTable.Load(readerNotReturned);
}
}
After that you have a Datatable containing your data. Ofcourse you can afterwards search for records in the Datatable any way you like.

Read data from all rows from Oracle and display in textbox using C#

I have Oracle data like this:
The table is named KETERANGAN and I want those data in textBox1. Not just one row but all rows. This my code used OracleDataReader
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT NOTES FROM KETERANGAN";
cmd.Connection = koneksidb.con;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["NOTES"].toString();
}
dr.Close();
I get: You're Cool.
I want: You're Cool, Amazing, Wonderful
use += instead of = which will append the result. you are currently replacing it.
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT NOTES FROM KETERANGAN";
cmd.Connection = koneksidb.con;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text += dr["NOTES"].toString() + ",";
}
dr.Close();
It could be done like this:
// wrap IDisposable into using
using (OracleCommand cmd = new OracleCommand()) {
cmd.Connection = koneksidb.con;
// Make SQL readable
cmd.CommandText =
#"SELECT Notes
FROM Keterangan";
// wrap IDisposable into using; do not close manually - dr.Close()
using (OracleDataReader dr = cmd.ExecuteReader()) {
// do not append string in loop - use SringBuilder
StringBuilder sb = new StringBuilder();
while (dr.Read()) {
if (sb.Length > 0) // <- do not put delimiter before the very first item
sb.Append(", "); // <- do you want a delimiter? Say, comma?
// ".ToString()" provides debug info, use Convert.ToString() instead
sb.Append(Convert.ToString(dr.GetValue(0)));
}
// Assign data once in order to prevent re-painting (and blinking)
textBox1.Text = sb.ToString();
}
}
Hope, the comments inside the routine explain the code enough.
Safe and optimized solution...
var notesBuilder = new StringBuilder();
const string SQL = #"SELECT NOTES FROM KETERANGAN";
using (var cmd = new OracleCommand(SQL, koneksidb.con))
{
using (OracleDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
notesBuilder.Append(dr["NOTES"]);
notesBuilder.AppendLine(",");
}
}
}
textBox1.Text = notesBuilder.ToString();
Or you can set the Multiline property on your textbox to true and use
textBox1.Lines.Add(dr["NOTES"].toString());

Using oledbdatatreader inside the oledbdatareader

I have code like
DatabaseConnection.MyExecuteNonQuery(comd);
cmd.CommandText = "select heads,formulla,fields from tbl_empsalstructear where empcode='" + emp.empid + "' order by headid";
OleDbDataReader rdr = DatabaseConnection.MyExecuteReader(cmd);
while (rdr.Read())
{
Here I have another function which returns a string value
string abc=function();
and then I use
string jkl=rdr[0].tostring()
which returns no value
and says no data in row n column but when I remove that function inside while it works properly and in that function I have another data reader that is closed
}
Maybe try checking for NULL values before trying to access the data.
The link above states;
Call this method to look for null column values before calling the typed get methods (for example, GetByte, GetChar, and so on) to avoid raising an error.
I typically use SqlDataReader, but an example of what I do is as follows. Note the rdr.IsDBNull call. Do that for any column that allows nulls;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnstring"].ConnectionString))
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = SQL_COURSE_COMPONENTS; // Constant to my SQL statement containing a parameter #CourseId
SqlParameter param = new SqlParameter();
param.ParameterName = "#CourseId";
param.Value = CourseId;
cmd.Parameters.Add(param);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
int CODE_ORDINAL = rdr.GetOrdinal("Code");
while (rdr.Read())
{
string code = rdr.IsDBNull(CODE_ORDINAL) ? (string)null : rdr.GetString(CODE_ORDINAL);
// .... Rest of the code here
}
}
}

Retrieving values from DB to Label in C#

I have created an Entity Framework application to retrieve Database values but i want to show them in individual labels instead of a gridview??
EmployEntities2 fd = new EmployEntities2();
int idToupdate = Convert.ToInt32(TextBox1.Text);
var jj = (from bn in fd.Contacts
where bn.Id == idToupdate
select bn);
GridView1.DataSource = jj;
GridView1.DataBind();
Established a connection
SqlConnection con = new SqlConnection("CONNECTION_STRING);
SqlCommand cmd = new SqlCommand();
and then,
cmd.CommandText = "select * from table where Condition ;
cmd.Connection = con
Label1.text = ((string)cmd.ExecuteScalar());
Try this one..
You should use SQLDataReader class. Base on what type of data you have in structure you should call a different method of the SQLDataReader object. For example, if you need to retrieve an integer value and display it in a label, this is the code sinppet to do it:
string queryString = "SELECT integer_value FROM table_name";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
label1.Text = reader.getSqlInt32(0).ToString();
}
reader.close();
}
This is the best I can do since you didn't provide additional info.
Check out this link for info on SqlDataReader class: SqlDataReader reference

MySqlCommand().ExecuteReader().GetString() does not work

I'm working with MySql in C# language.
I'm trying get some data out of my database.
The fields are organized like:
foo baa
38737 22222
I need to get value of foo if my hash is equal to baa
I tried this:
My code(not working)
MySqlConnection con = new MySqlConnection("Server=localhost;Database=test;Uid=user;Pwd=pass;");
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = string.Format("SELECT * FROM info WHERE baa = '{0}'", Hash); ;
cmd.Connection = con;
MySqlDataReader reader = cmd.ExecuteReader();
String res = reader.GetString(0);
I'm getting the following error:
Invalid attempt to access a field before calling Read()
Can someone point out my error?
Thanks in advance.
You are missing a reader.Read() call:
MySqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
String res = reader.GetString(0);
//...
}
Try:
string res;
using(MySqlDataReader reader = cmd.ExecuteReader())
{
if(reader.Read())
res = reader.GetString(0);
else
res = "not found";
}
If you change the SQL command to return a single value, for example:
"SELECT foo FROM info WHERE baa = '{0}' LIMIT 1"
then you can also use cmd.ExecuteScalar():
string res = cmd.ExecuteScalar().ToString();

Categories