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

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

Related

How to return specific row from database that include image path

I write below code that correctly returns an image that its path stored in the database.
[HttpGet("{id}")]
public IActionResult RetrieveFile(int id)
{
string pathImage = "";
DataTable table = new DataTable();
string query = #"select image from mydb.courses where id=#id";
string sqlDataSource = _configuration.GetConnectionString("UsersAppCon");
MySqlDataReader myReader;
using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
{
mycon.Open();
using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
{
myCommand.Parameters.AddWithValue("#id", id);
pathImage = (string)myCommand.ExecuteScalar();
mycon.Close();
}
}
var path = #$"{pathImage}";
var fs = new FileStream(path, FileMode.Open);
return File(fs, "image/jpeg");
}
Furthermore, I want to return the id, price, and name with the image from the database and send it to the client.
What changes should I make to the above code to send me What I want?
You cannot use ExecuteScalar, but you need to call ExecuteReader to get back an MySqlDataReader and then get the single inputs from the reader fields. and of course, you should change the query to get the required fields
string query = #"select id,price,name,image from mydb.courses where id=#id";
string sqlDataSource = _configuration.GetConnectionString("UsersAppCon");
using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
{
mycon.Open();
using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
{
myCommand.Parameters.AddWithValue("#id", id);
// Then you use the reader to get the single field values
using(MySqlDataReader myReader = myCommand.ExecuteReader())
{
// Always check if the where clause produces records to read
if(myReader.Read())
{
// I have assumed the datatype for the fields. Change GetXXXX if different
pathImage = myReader.GetString("image");
id = myReader.GetInt32("id");
price = myReader.GetDecimal("price");
name = myReader.GetString("name");
}
}
}
}
Notice that you don't need to close the connection when it is declared inside a using statement. Also it is better to not use AddWithValue albeit in case of integers its problems are not relevant and MySql seems to be a bit more resilient than other db

I am not able to get the data from database into a textbox

string connstring = ConfigurationManager.ConnectionStrings["electionConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
updatedata();
}
public void updatedata(){
int ward_no =Convert.ToInt32((Session["wardno"]));
string query = "select ward_no,part_no,part_leader1_name,part_leader1_mob,part_leader2_name,part_leader2_mob,t_streets,t_families,t_electoral,t_male,t_female,t_others from f_field_details where ward_no=#ward_no";
MySqlConnection con = new MySqlConnection(connstring);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#ward_no", ward_no);
MySqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
if (reader.Read())
{
txtward.Text = reader["ward_no"].ToString();
txtpart.Text = reader["part_no"].ToString();
txtleadername.Text = reader["part_leader1_name"].ToString();
txtphne1.Text = reader["part_leader1_mob"].ToString();
txtname1.Text = reader["part_leader2_name"].ToString();
txtphneno.Text = reader["part_leader2_mob"].ToString();
txtstreets.Text = reader["t_streets"].ToString();
txtfamilies.Text =reader["t_families"].ToString();
txttotvotes.Text = reader["t_electoral"].ToString();
txtMen.Text = reader["t_male"].ToString();
txtWomen.Text = reader["t_female"].ToString();
txtothers.Text = reader["t_others"].ToString();
}
}
}
this is my coding, i am getting the data from the database after the user is entering the data in the previous page after they click the submit button I am redirecting them into the next page that is this page, the issue is the data is getting inserted into the database but will retrieving the data from the database is not working. to get the data am using a where condition in the query and the object for the condition is coming from the previous page using session. the issue is the data is not displayed in the textboxes
There are few corrections in your code:
The session["string"] will return on object, that may or maynot be convertiable as an integer so better to use int.TryParse() instead for Convert.To..().
Reader may get null reference if reader has no rows, so i suggest you to check for reader.HasRows before accessing value from it. or use While(reader.Read()):
Retrieving data using a DataReader involves creating an instance of
the Command object and then creating a DataReader by calling
Command.ExecuteReader to retrieve rows from a data source. The
following example illustrates using a DataReader where reader
represents a valid DataReader and command represents a valid Command
object.
Use Parameters.Add() instead for Parameters.AddWithValue()
So your code looks like this(and this may solve your problem too):
int ward_no=0;
int.TryParse(Session["wardno"].ToString(), out ward_no);
string query = "select ward_no,part_no,part_leader1_name,part_leader1_mob,part_leader2_name,part_leader2_mob,t_streets,t_families,t_electoral,t_male,t_female,t_others from f_field_details where ward_no=#ward_no";
MySqlConnection con = new MySqlConnection(connstring);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.Add("#ward_no", MySqlDbType.Int32).Value = ward_no; //this will be the type of field
MySqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
while (reader.Read())
{
// assign values here
}

cannot implicitly convert type 'int' to 'system.data.dataset'

Hi all, please I need your help, I am trying to execute a query and put all the retrieved data in a data set, but I get this error "cannot implicitly convert type 'int' to 'system.data.dataset'"
Here's the code:
// this is a small piece of the sql
String Astra_conn = ConfigurationManager.ConnectionStrings["AstraSeverConnection"].ConnectionString;
System.Text.StringBuilder sql = new System.Text.StringBuilder();
sql.Append(" SELECT ROWNUM AS ID, institution, LPAD (a.zone_name, 3, '0') AS campus, ");
sql.Append(" term_name AS term, student_instance_id AS student_id, subject, course, ");
sql.Append(" section_name AS section_num, offering AS title, ");
//Its OracleConnection because it is an Oracle server otherwise, it would be SqlConnection.
DataSet rs = new DataSet();
OracleConnection Astra_db_Conn = new OracleConnection(Astra_conn);
string myquery = sql.ToString();
OracleCommand cmd = new OracleCommand(myquery);
Astra_db_Conn.Open();
try
{
SqlDataAdapter adpt = new SqlDataAdapter();
rs = cmd.ExecuteNonQuery(); // this is where is get the error.
adpt.Fill(rs);
}
catch(Exception e)
{
log.Error("*** ERROR *** IRISExportQueries.loadStudentInfoLearningSites():" + e);
}
I've also tried
Astra_db_Conn.Open();
try
{
SqlDataReader reader = new SqlDataAdapter();
reader = cmd.ExecuteNonQuery(); // this is where is get the error.
}
catch(Exception e)
{
log.Error(&quot;*** ERROR *** IRISExportQueries.loadStudentInfoLearningSites():&quot; + e);</pre>
}
Then I get the error: "cannot implicitly convert type 'int' to 'System.Data.SqlClient.SqlDataReader'"
Thanks your help will be very much appreciated.
The problem is that ExecuteNonQuery returns the number of affected rows (an integer) and not a DataSet or DataReader. I'm afraid you're not using ADO.NET components correctly.
These 2 lines are enough to fill a DataSet
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(rs);
In any case this is not your only problem, you're mixing Sql* ADO.NET components with Oracle*ones. Adapter should be OracleDataAdapter
OracleDataAdapter adpt = new OracleDataAdapter(cmd);
adpt.Fill(rs);
Something else: you're never assigning the connection to the command. You should do
OracleCommand cmd = new OracleCommand(myquery, Astra_db_Conn);
And at last but not least important, dispose every instance of classes implementing IDisposable interface, otherwise unmanaged resources as connections to datasase won't be released.
This is the final version applying all my suggestions
var rs = new DataSet();
string myquery = sql.ToString();
using (var Astra_db_Conn = new OracleConnection(Astra_conn))
using (var cmd = new OracleCommand(myquery, Astra_db_Conn))
using (var adpt = new OracleDataAdapter(cmd))
{
Astra_db_Conn.Open();
adpt.Fill(rs);
}
The method ExecuteNonQuery() returns an int with the number of rows that are affected by the command.
To access the data from the query you should see this existing answer: Direct method from SQL command text to DataSet.
SqlDataAdapter adapt= new SqlDataAdapter(cmd.CommandText,cmd.Connection);
adapt.Fill(rs, " Your Table name as it is in database inside this quotation");
now u can give source to ur data views like datalist or datatable or gridview as following
Datalist1.DataSource= rs.Tables("Your Table name as it is in database inside the above q mark")
now atlast jst bind it
Datalist1.DataBind();

connect and read .MDB item with C#

Is it possible to connect to a local MDB file and pick a single bit of info out of it ?
I have a table in a .mbd file with a single bit of info in it. I would like to have that record be output into a disabled textbox for a reference. I believe I can get the DB open, and run the query but no idea what I need to read from it.
thanks
var myDataTable = new DataTable();
using (var conection = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" + "data source=C:\\menus\\newmenus\\menu.mdb;Password=****"))
{
conection.Open();
var query = "Select siteid From n_user";
var adapter = new OleDbDataAdapter(query, conection);
OleDbCommandBuilder oleDbCommandBuilder = new OleDbCommandBuilder(adapter);
}
To simply read a single field on your database table you could use an OleDbDataReader that could loop over the result and return the field required..
var myDataTable = new DataTable();
using (var conection = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" + "data source=C:\\menus\\newmenus\\menu.mdb;Password=****"))
{
conection.Open();
var query = "Select siteid From n_user";
var command = new OleDbCommand(query, conection);
var reader = command.ExecuteReader();
while(reader.Read())
textBox1.Text = reader[0].ToString();
}
if you have just one record and just one field then a better solution is the method ExecuteScalar
conection.Open();
// A query that returns just one record composed of just one field
var query = "Select siteid From n_user where userid=1";
var command = new OleDbCommand(query, conection);
int result = (int)command.ExecuteScalar(); // Supposing that siteid is an integer
Probably I should also mention that ExecuteScalar returns null if the query doesn't find a match for the userid, so it is better to be careful with the conversion here
object result = command.ExecuteScalar();
if( result != null)
int userID = (int)result;
.....
Yes very possible. Just have the adapter fill the DataTable, also I don't think you'll need the OleDbCommandBuilder.
using (var conection = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" + "data source=C:\\menus\\newmenus\\menu.mdb;Password=****"))
{
conection.Open();
var query = "Select siteid From n_user";
var adapter = new OleDbDataAdapter(query, conection);
adapter.Fill(myDataTable);
myTextBox.Text = myDataTable.Rows[0][0].ToString();
}
Also I think using ExecuteScalar would be a better solution, but my answer was tailored to the objects you had already instantiated.
You could use OleDbCommand.ExecuteScalar to retrieve a single value. It is returned as an object and you could cast it to the correct type.
Are you looking for stm like this?
OleDbCommand cmd = new OleDbCommand();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
// read ur stuff here.
}

How do I get an DataTable from IDataReader?

I'm trying to get a DataTable or DataSet from an IDataReader, but I'm failing. Here's the code:
string sql = #"SELECT ID, DOCNUMBER FROM TBDOCUMENT";
using (IDbConnection conn = CreateConnection(provider, connectionString))
{
conn.Open();
using (IDbCommand command = conn.CreateCommand())
{
command.CommandText = sql;
IDataReader reader = command.ExecuteReader();
using (reader)
{
while (reader.Read())
{
long key = reader.GetInt64(0);
decimal value = reader.GetDecimal(1);
}
}
}
}
I'm using IDbConnection and IDbCommand because it will works with three different databases (the method CreateConnection(provider, connectionString) gets the specific type of connection according to the database).
My query gets an ID (as Int64) and a DocNumber (as Decimal), but every time I try to get the decimal value, it throws an OverflowException with a message: "Conversion overflows." Both of values are important to me, but I don't know how do I get these values.
Actually, the code I'm not trying to convert to a DataTable, I have to get the value of the two without exception.
Some help?
Though I haven't check by executing but it should work...
// Load the data into the existing DataSet.
DataTableReader reader = GetReader();
dataSet.Load(reader, LoadOption.OverwriteChanges,
customerTable, productTable);
// Load the data into the DataTable.
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(dr);

Categories