Get SQL data And show it in a text box? - c#

In the last few days I am trying to get data from my SQL table and get it into my textbox.
The table name : "check".
The code I am using :
SqlDataReader myReader = null;
connection = new SqlConnection(System.Configuration.ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString);
connection.Open();
var command = new SqlCommand("SELECT * FROM [check]", connection);
myReader = command.ExecuteReader();
while (myReader.Read())
{
TextBox1.Text = myReader.ToString();
}
connection.Close();
I am getting nothing as a result. Anyone know why? Maybe I am not calling the SQL correctly?

using (var connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT ColumnName FROM [check]";
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
TextBox1.Text = reader["ColumnName"].ToString();
}
}
Some comments:
don't use *, specify only those fields that you need
use using - less code, guaranteed disposal
I assume this is a test program, otherwise it does not make sense to reset Text to a in the loop

TextBox1.Text = myReader["fieldname"].ToString();
also I think you can change while with if because for every row from your table you'll overwrite textbox text!

Try this:
TextBox1.AppendText(myReader["columnname"].ToString());

Related

How to use C# connect to mysql and get json data?

As mentioned above:
I'm using C# to connect to a MySQL database and I want to read JSON data type.
I use the method MySqlCommand.ExecuteReader:
using (MySqlConnection sconn = new MySqlConnection(sqlConnectString))
{
sconn.Open();
String sql_Command = #"SELECT `id` FROM orders.jsontest;";
using (MySqlCommand scmd = new MySqlCommand(sql_Command, sconn))
{
**MySqlDataReader sdr = scmd.ExecuteReader();** // fatal error
DataTable datatable = new DataTable();
// ...
}
}
Can it be that I cannot use ExecuteReader here?
I know this question is old, but just in case you do not yet have a solution to your problem or anyone else encounters a similar problem, the following code should work for you:
private IEnumerable<int> GetIds()
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT id FROM jsontest"; // Assuming that `orders` is your database, then you do not need to specify it here.
using (MySqlCommand command = new MySqlCommand(commandText, connection))
{
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
yield return reader.GetInt32(0);
}
}
}
}
Now what you should pay attention to is this line
while (reader.Read())
which fetches results from the jsontest table as long as the MySqlDataReader can still read valid results and this line
yield return reader.GetInt32(0);
which instructs the reader to get and return each record of the fetched table one at a time as an Int32 (int). You need to change this if your tables column type is not INT.
Since you selected just one column (i.e. "SELECT id"), the parameter is 0, because your fetched resul table consists of one column only.
Additionally, in your code you seem to want to get the results as a DataTable; if so, you should use MySqlDataAdapter instead of the MySqlDataReader as follows:
DataTable resultTable = new DataTable("ResultTable");
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
adapter.Fill(table);
Correct your sql command
String sql_Command = #"SELECT id FROM orders.jsontest";

Put content of access database into two listboxs

Hi I have a database with two tables: 1.) Country (Table name: 2.) Website
Every country has 1 or more websites.
I am trying to make a C# WindowsForm Application where I want the User first to select a country from the first listbox1 and then all the Websites will in the second listbox2 based on the database.. I somehow can't display all the countries in the first textbox using a select statement: the code is the following
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT CountryName FROM Countries ";
//whenever you want to get some data from the database
using (OleDbDataReader reader = command.ExecuteReader())
{
listBox.Items.Add(reader);
}
//OleDbDataReader reader = command.ExecuteReader();
connection.Close();
}
catch(Exception l)
{
MessageBox.Show("Error:" + l);
}
This code doesn't show the items in the listbox.
Can someone please advise ?
You probably want to get your data from the reader and convert it to an object before you put it in the listbox. You can get the value for each column by reader["columnname"]. Dont forget that you also need to convert each value to its proper type, you will probably find all types of conversion you need in System.Convert.
With your scenario in mind you should be able to do
using (OleDbDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
listBox.Items.Add(reader["CountryName"].ToString());
}
}
You are trying to add the OleDbDataReader as a listbox item instead of using it to read the data, here is an example of how to use it :
try
{
connection.Open();
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
command.CommandText = "SELECT CountryName FROM Countries ";
//whenever you want to get some data from the database
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.NextResult())
{
listBox.Items.Add(reader.GetString(0));
}
}
}
}
catch (Exception l)
{
MessageBox.Show("Error:" + l);
}
finally
{
connection.Close();
}

Specifies that I have problems with my conn.open and my Conn.Close

this is how I select some content twice and when I get into the middle to select so like that it gives me trouble to select something on file.
The problem I have never seen before,
I think it's something with conn.open() and Conn.Close()
my code looks like this:
int prisId = Convert.ToInt32(Request.QueryString["Id"]);
cmd.Parameters.AddWithValue("#ppId", prisId);
cmd.CommandText = "SELECT priser FROM Priser WHERE Id = #ppId;";
conn.Open();
SqlDataReader readerPriser = cmd.ExecuteReader();
if (readerPriser.Read())
{
PanelerrorHandelsbetingelser.Visible = false;
string Brugerid = Session["id"].ToString();
cmd.Parameters.AddWithValue("#brugerid", Brugerid);
cmd.CommandText = "SELECT id, brugernavn, fornavn, efternavn FROM brugere WHERE Id = #brugerid;";
SqlDataReader readerBrugerid = cmd.ExecuteReader();
if (readerPriser.Read())
{
Session["id"] = readerBrugerid["id"].ToString();
Session["brugernavn"] = readerBrugerid["brugernavn"].ToString();
Session["fornavn"] = readerBrugerid["fornavn"].ToString();
Session["efternavn"] = readerBrugerid["efternavn"].ToString();
Session["adresse"] = TextBoxAdresse.Text;
Session["post"] = TextBoxPost.Text;
Session["telefon"] = TextBoxTelefon.Text;
Session["prisen"] = readerPriser["priser"].ToString();
LabelErrorBuyNow.Text = " - Yeaaa Jesper!";
}
else
{
LabelErrorBuyNow.Text = " - Der findes intet med dit brugerid!";
}
}
conn.Close();
problems come after line 9-10
The problem is such that it appears this one mistake on my part: There is already an open DataReader associated with this Command which must be closed first.
Always remember to release resources after they are used. So at the method end, you should:
cmd.Parameters.Clear();
readerPriser.Close();
conn.Close();
The exception tells you exactly what is wrong.
You have tried to run two SqlDataReaders over the same connection without either specifying MultipleActiveResultSets=True in your connection string or else first closing the first reader.
You have three options:
Use a second connection to run the second SqlDataReader.
Add "MultipleActiveResultSets=True" to your connection string.
Close the first SqlDataReader before using the second.
You need to close the readerPriser first be
readerPriser.Close();
Then affiliate the same command with next reader.
Always close the readers after using them.
There are two problems here. First of all, you are not placing all of your IDisposable objects into using blocks. Second, you are reusing the same SqlCommand for different queries. Third, your second Read call is using the wrong SqlDataReader.
Try
using (SqlConnection conn = new SqlConnection(...)){
conn.Open();
using (SqlCommand selectPriser = new SqlCommand("SELECT priser FROM Priser WHERE Id = #ppId;", conn))
{
selectPriser.Parameters.AddWithValue("#ppId", prisId);
using (SqlDataReader readerPriser = selectPriser.ExecuteReader())
{
if (readerPriser.Read())
{
// ...
using (SqlCommand selectBrugere = new SqlCommand("SELECT id, brugernavn, fornavn, efternavn FROM brugere WHERE Id = #brugerid;"){
string Brugerid = Session["id"].ToString();
selectBrugere.Parameters.AddWithValue("#brugerid", Brugerid);
using (SqlDataReader readerBrugerid = selectBrugere.ExecuteReader()){
if (readerBrugerid.Read()){
// ...
}
}
}
}
}
}
}

C# SQL multiple query results into diffrent textbox

So I'm having this :
Conn.Open();
SqlCommand Comm3 = new SqlCommand("SELECT answer" + " FROM answers" + " WHERE id_answer=5" , Conn);
SqlDataReader DR3 = Comm3.ExecuteReader();
And there is multiple results,how can I now move each of them in diffrent textbox (i already created textboxes? Till now i only managed to get same result into them.
this is normally how i do it....
SqlConnection cn = new SqlConnection("my connection string");
cn.Open();
string sql = "select * from table where column = whatever";
using (SqlCommand cmd = new SqlCommand(sql,cn))
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
myTextBox1.Text = (string)dr["Column1"];
myTextBox2.Text = (string)dr["Column2"];
myTextBox3.Text = (string)dr["Column3"];
}
dr.Close();
}
cn.Close();
just make sure you are aiming the right column name while looping through them, and cast correctly.
You need to loop through each of the item in the Database table. Think of a foreach loop, where you simply just go through each item and work on it similarly.
Here is a sample for that,
// Create new SqlDataReader object and read data from the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// while there is another record present
while (reader.Read())
{
// write the data on to the screen
textBox.Text = reader[0];
}
}
This will add the value of reader's first column (answer) to the textBox. Now make sure you're calling correct textBox to add the value to.
http://www.codeproject.com/Articles/823854/How-to-connect-SQL-Database-to-your-Csharp-program Do give this article a read.

MySql "Select Where" and C#

How can i read the return value from "Select Where" statement , every time i run no return value appear in the label, and no syntax error.
command.CommandText = "select product_price from product where product_name='"+x+"';";
connection.Open();
Reader = command.ExecuteReader();
while(Reader.Read()){
Price_label.Content = "" + Reader.GetString(0);
}
connection.Close();
If the product_price column is not of type TEXT in MySQL, the Reader.GetString(0) will (depending on how the reader was implemented by Oracle) throw an Exception or return an empty string. I would think the latter is happening.
Retrieving the value through a DataReader requires you to know the data type. You can not simply read a string for every type of field. For example, if the field in the database is an Integer, you need to use GetInt32(...). If it is a DateTime use GetDateTime(...). Using GetString on a DateTime field won't work.
EDIT
This is how I'd write this query:
using (MySqlConnection connection = new MySqlConnection(...))
{
connection.Open();
using (MySqlCommand cmd = new MySqlCommand("select product_price from product where product_name='#pname';", connection))
{
cmd.Parameters.AddWithValue("#pname", x);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
while (reader.Read())
sb.Append(reader.GetInt32(0).ToString());
Price_label.Content = sb.ToString();
}
}
}
To append to my comment, your approach has three problems which are not part of your problem:
SQL-Injection, always use parameterized queries.
Leaking resources, IDisposable-Objects need to be treated properly.
Bad habits, "" + string for casting is...uhhh...not good and not necessary.
So, a more correct version for your code would look like this:
// using utilizes the IDisposable-Interface, whcih exists to limit the lifetime
// of certain objects, especially those which use native resources which
// otherwise might be floating around.
using(YourConnectionType connection = new YourConnectionType("connectionstring"))
{
connection.Open(); // You might want to have this in a try{}catch()-block.
using(YourCommandType command = connection.CreateCommand())
{
command.CommandText = "select product_price from product where product_name=#NAME;";
command.Parameters.Add("NAME", YourTypes.VarChar);
command.Parameters[0].Value = x; // For your own sanity sake, rename that variable!
using(YourReaderType reader = command.ExecuteReader())
{
while(reader.Read()) // If you're expecting only one line, change this to if(reader.Read()).
{
Price_label.Content = reader.GetString(0);
}
}
}
} // No need to close the conenction explicit, at this point connection.Dispose()
// will be called, which is the same as connection.Close().
you have to create a variable of your reader
command.CommandText = "select product_price from product where product_name='"+x+"';";
try {
connection.Open();
SqlReader reader = command.ExecuteReader();
while(reader.Read()){
Price_label.Content = "" + Reader.GetString(0);
}
} catch (Exception) {}
finally {
connection.Close();
}
You should write #pname without '' otherwise it won't work.
instead of:
select product_price from product where product_name='#pname'
you should write like this:
select product_price from product where product_name=#pname

Categories