Creating Json string in C# with column headings - c#

the code below is working perfectly but I would like to know a way to pull the column headings out too? I would like it inside my while loop if possible. Hopefully someone here can help.
Thanks, James.
namespace WorldViewNet.include
{
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
object data = LoadAPI(context);
string jsonData = JsonConvert.SerializeObject(data);
context.Response.Write(jsonData);
}
public List<object[]> LoadAPI(HttpContext context)
{
List<object[]> list = new List<object[]>();
SqlConnection sqlConnection1 = new SqlConnection(globalLibrary.NewConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
string tablename = context.Request.QueryString["tablename"];
string maybeID = context.Request.QueryString["ID"];
cmd.CommandText = "SELECT * FROM " + tablename;
if (maybeID != null)
{
cmd.CommandText += " WHERE " + tablename + "ID =" + maybeID;
}
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
object[] row = new object[23];
reader.GetValues(row);
list.Add(row);
}
sqlConnection1.Close();
return list;
}
public bool IsReusable
{
get
{
return false;
}
}
}
}

You should be able to simply do this:
reader = cmd.ExecuteReader();
var columns = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList();
columns should be a List now of all your column names.
If you need a non-Linq way to do this:
reader = cmd.ExecuteReader();
var columns = new List<string>();
for(int z=0;z<reader.FieldCount;z++)
{
columns.Add(reader.GetName(z));
}

Related

How to concatenate query result in C#

I want to concatenate the query result in c#. Below is the resulting image
In my code, I have done
using (MySqlConnection cn = new MySqlConnection(conn.ConnectionString))
{
string query = "SELECT m.`read_param` FROM mdc_request m WHERE m.`row_id` = #row_id";
cn.Open();
MySqlCommand cmd = new MySqlCommand(query, cn);
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#row_id", iterations.row_id);
reader = cmd.ExecuteReader();
while (reader.Read())
{
// here I want to save the result in one single variable
}
}
Update 1
As per #Rahul answer, I have done the following
public async Task YtlbusMethod(List<Iterations> ytlbus)
{
MySqlConnection cn = null;
int limitRequest = 10;
for (int i = 10; i > 0; i--)
{
foreach (var item in ytlbus)
{
using (cn = new MySqlConnection(conn.ConnectionString))
{
string query = "SELECT m.`time` FROM `mdc_meter_config` m WHERE m.`row_id` = #row_id";
cn.Open();
MySqlCommand cmd = new MySqlCommand(query, cn);
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#row_id", item.row_id);
reader = cmd.ExecuteReader();
while (reader.Read())
{
string time = (string)reader["time"];
if(item.time == time)
{
int sleeptime = Convert.ToInt32(item.time);
sleeptime = sleeptime * 1000;
Thread.Sleep(sleeptime);
Task.Factory.StartNew(() => PortHitmethod(item));
}
}
}
cn.Close();
// select query kerni hy ..jis main wohi data ay jo tu yahan pass ker raha hy... where k ander just tuny row id pass kerni hy.
//if(item.time== query main jo time aya hy woh)
//{
//}
}
}
}
public async Task PortHitmethod(Iterations iterations)
{
MySqlConnection cn = null;
List<string> data = new List<string>();
using (cn = new MySqlConnection(conn.ConnectionString))
{
string query = "SELECT m.`read_param` FROM mdc_request m WHERE m.`row_id` = #row_id";
cn.Open();
MySqlCommand cmd = new MySqlCommand(query, cn);
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#row_id", iterations.row_id);
reader = cmd.ExecuteReader();
while (reader.Read())
{
data.Add(reader["read_param"].ToString());
}
}
cn.Close();
var single = string.Join("", data);
}
Now the issue that I am facing is that I am unable to get all the rows data. The total rows are 9 but I am getting less than that
How can I achieve this? Any help would be highly appreciated.
Looks like those are integer value then you can do something like
List<int> data = new List<int>;
while (reader.Read())
{
data.Add(int.Parse(reader["read_param"].ToString()));
}
Then you can use string.Join() method like
var single = string.Join(",", data);
Based on #Rahul, your code should be:
Your update 1 is different code.
What do you want to achieve here.
List<string> data = new List<string>();
using (MySqlConnection cn = new MySqlConnection(conn.ConnectionString))
{
string query = "SELECT m.`read_param` FROM mdc_request m WHERE m.`row_id` = #row_id";
cn.Open();
MySqlCommand cmd = new MySqlCommand(query, cn);
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#row_id", iterations.row_id);
reader = cmd.ExecuteReader();
while (reader.Read())
{
data.Add(reader["read_param"].ToString());
}
}
var single = string.Join("", data);

asp.net web api with Mysql database

I have a background in PHP and bump into a problem while trying out ASP.NET webAPI.
I have a MySQL database and a table that contains some files information.
Now i want to make a "SELECT * FROM Files" and see the result in XML.
How can i render the result of the query that is returned?
This is my code at the moment,
The Model:
namespace ProductsApp.Models
{
public class File
{
public int Id {get; set;}
public string Text {get; set;}
}
}
The Controller:
public IEnumerable<File> Get()
{
try
{
command = conn.CreateCommand();
command.CommandText = "SELECT * FROM Files";
conn.Open();
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//How to output the rows ????
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return null; // return the list
}
Making some assumptions about your File Table, this is how you get the data
public IEnumerable<File> Get()
{
List<File> list = new List<File>();
try
{
command = conn.CreateCommand();
command.CommandText = "SELECT * FROM Files";
conn.Open();
using(MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//How to output the rows ????
int id = (int) reader["Id"];//Assuming column name is 'Id' and value if typeof(int)
string text = (string) reader["Text"];//Assuming column name is `Text` and typeof(string)
var file = new File {Id = id, Text = text};
list.Add(file);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return list; // return the list
}
As for the xml that is a formatting setting that needs to be allowed on the request.
Given the default setup of WebApi once the client making the call requests text/xml as the content type then the result should be parsed to xml and returned to the client.
If it is you want to force the response to always be xml then you need to make some changes to the response. One way is to set the Content-Type header before returning your result.
Response.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml;charset=utf-8");
There are other ways you can do this and there are many answers on SO that will be able to show you.
Webconfig:
public static MySqlConnection conn()
{
string conn_string = "server=localhost;port=3306;database=testmvc;username=root;password=root;";
MySqlConnection conn = new MySqlConnection(conn_string);
return conn;
}
Controller :
public MySqlConnection con = WebApiConfig.conn();
public IHttpActionResult GetAllProduct()
{
IList<product> pro = null;
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from product", con);
cmd.CommandType = CommandType.Text;
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
pro = ds.Tables[0].AsEnumerable().Select(dataRow => new product { Pname = dataRow.Field<string>("pname"), Pid = dataRow.Field<int>("pid"), Pprice = dataRow.Field<decimal>("pprice") }).ToList();
}
finally
{
con.Close();
}
if (pro.Count == 0)
{
return NotFound();
}
return Ok(pro);
}
public IHttpActionResult PostNewProduct(product pro)
{
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT MAX(pid) from product";
cmd.CommandType = CommandType.Text;
int maxid = Convert.ToInt16(cmd.ExecuteScalar().ToString())+1;
cmd.CommandText = "insert into product values(" + maxid + ",'" + pro.Pname + "'," + pro.Pprice + ")";
cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}
return Ok();
}
public IHttpActionResult PutOldProduct(product pro)
{
string sql = "update product set pname='" + pro.Pname + "',pprice=" + pro.Pprice + " where pid=" + pro.Pid + "";
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand(sql, con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}
return Ok();
}
public IHttpActionResult Delete(int id)
{
string sql = "delete from product where pid=" + id + "";
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand(sql, con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}
return Ok();
}

How to use SqlCommand and SqlDataReader to return a Json result in C#

I'm trying to use a SQL query in SqlCommand and I'd like to see the complete result set that is returned from SQL Server database, and return Json format after that.
So here is the code in controller:
public ActionResult GetAllSummary()
{
string connectionString ="Data Source=...;Initial Catalog=...;Integrated Security=True";
string query = "SELECT v.date, v.name, v.numbers FROM view as v GROUP BY v.date,v.mane,v.numbers ORDER BY v.date,v.mane,v.numbers";
using(SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, conn);
try {
conn.Open();
SqlDataReader reader = command.ExecuteReader();
// In this part below, I want the SqlDataReader to
// read all of the records from database returned,
// and I want the result to be returned as Array or
// Json type, but I don't know how to write this part.
while(reader.Read())
{
ArrayList result = new ArrayList();
foreach(int i in reader)
// this line below was the code I wrote before.
// But since my query returns multiple
// types (datetime, string, decimal, etc..),
// I don't know what C# command I can use to return
// the results in foreach loop. Or say I even don't
// need a for/foreach loop.
result.Add(reader.GetValue(i));
return Json(result, JsonRequestBehavior.AllowGet);
}
reader.Close();
}
catch(Exception ex)
{
var error = ex.Message;
return View(error);
}
}
return View();
}
Anyone can help me to make this work? I will be greatly appreciated.
Kevin
public class data {
public DateTime date {get;set;}
public string name {get;set;}
public int numbers {get;set;}
}
public ActionResult GetAllSummary()
{
string connectionString ="Data Source=...;Initial Catalog=...;Integrated Security=True";
string query = "SELECT DISTINCT v.date, v.name, v.numbers FROM view as v ORDER BY v.date,v.name,v.numbers";
using(SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, conn);
try {
conn.Open();
SqlDataReader reader = command.ExecuteReader();
// In this part below, I want the SqlDataReader to
// read all of the records from database returned,
// and I want the result to be returned as Array or
// Json type, but I don't know how to write this part.
while(reader.Read())
{
List<data> result = new List<data>();
var d=new data();
d.date=reader[0]; // Probably needs fixing
d.name=reader[1]; // Probably needs fixing
d.numbers=reader[2]; // Probably needs fixing
result.Add(data);
}
reader.Close();
return Json(result, JsonRequestBehavior.AllowGet);
}
catch(Exception ex)
{
var error = ex.Message;
return View(error);
}
}
return View();
}
or
public class data {
public DateTime date {get;set;}
public string name {get;set;}
public int numbers {get;set;}
}
public ActionResult GetAllSummary()
{
string connectionString ="Data Source=...;Initial Catalog=...;Integrated Security=True";
string query = "SELECT DISTINCT v.date, v.name, v.numbers FROM view as v ORDER BY v.date,v.name,v.numbers";
using(SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, conn);
try {
conn.Open();
SqlDataReader reader = command.ExecuteReader();
var dt=new DataTable();
dt.Load(myDataReader);
List<DataRow> result=dt.AsEnumerable().ToList();
reader.Close();
return Json(result, JsonRequestBehavior.AllowGet);
}
catch(Exception ex)
{
var error = ex.Message;
return View(error);
}
}
return View();
}
or (just the interesting part):
var dt=new DataTable();
dt.Load(myDataReader);
object[] result = new object[dt.Rows.Count + 1];
for (int i = 0; i <= dt.Rows.Count - 1; i++) {
result[i] = dt.Rows[i].ItemArray;
}
You can use this extension:
public static string ExecuteToJson(this SqlCommand cmd)
{
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
using (DataTable dt = new DataTable())
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return JsonConvert.SerializeObject(rows);
}
}
}
and the usage:
string connectionString = "** connstr **";
string query = "SELECT * FROM `table`";
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, conn))
{
string json = command.ExecuteToJson();
}
}
}
catch (Exception)
{
}

Saving database values as variables

I can't figure out how to save individual data from an Access database into variables.
I understand that you can save variables like this:
int memberID;
cmd.CommandText = "SELECT * FROM MemberDetails WHERE [MemberID] =#MemberID";
cmd.Parameters.AddWithValue("#MemberID", memberID);
try
{
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
lblName.Text = (memberID);
}
con.Close();
}
catch (Exception)
{
throw;
}
However I want to save all the data into separate variables, something like this:
cmd.CommandText = "SELECT [MemberID] = #MemberID, [Name] = #Name, [Surname] = #Surname";
cmd.Parameters.AddWithValue("#MemberID", memberID);
cmd.Parameters.AddWithValue("#Name", name);
cmd.Parameters.AddWithValue("#Surname", surname);
This obviously doesn't work (otherwise I wouldn't be here) but is anything like this possible and how would I go about doing this?
Maybe have a look at this great tutorial from Microsoft, it explains on how to query an MS Access database with C# and how to process the results: https://msdn.microsoft.com/en-us/library/ms971485.aspx
What you could do to achieve the desired result is something like this (this is a slightly modified example from the article mentioned above):
OleDbConnection conn = null;
OleDbDataReader reader = null;
try
{
conn = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0; " +
"Data Source=" + Server.MapPath("MyDataFolder/MyAccessDb.mdb"));
conn.Open();
OleDbCommand cmd =
new OleDbCommand("Select MemberID, Name, Surname FROM MemberDetails WHERE MemberID = #MemberID", conn);
cmd.Parameters.AddWithValue("#MemberID", memberID);
reader = cmd.ExecuteReader();
while(reader.Read())
{
memberID = reader.GetInt32(reader.GetOrdinal("MemberID"));
name = reader["Name"].ToString();
surname = reader["Surname"].ToString();
}
}
finally
{
if (reader != null) reader.Close();
if (conn != null) conn.Close();
}
Be carefull though, this will only work correctly when there is only one result returned in be the database query. When multiple records are returned only the last will be stored in the variables.
When you need to capture multiple results you will probably want to create a Member class, create an instance for each record and add the instance to a members list. Something like this:
public class Member
{
public int MemberId {get; set;}
public string Name {get; set;}
public string Surname {get; set;}
}
public IList<Member> GetMembers()
{
OleDbConnection conn = null;
OleDbDataReader reader = null;
try
{
conn = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0; " +
"Data Source=" + Server.MapPath("MyDataFolder/MyAccessDb.mdb"));
conn.Open();
OleDbCommand cmd =
new OleDbCommand("Select MemberID, Name, Surname FROM MemberDetails", conn);
reader = cmd.ExecuteReader();
var members = new List<Member>();
while(reader.Read())
{
var member = new Member();
member.MemberID = reader.GetInt32(reader.GetOrdinal("MemberID"));
member.Name = reader["Name"].ToString();
member.Surname = reader["Surname"].ToString();
members.Add(member);
}
return members;
}
finally
{
if (reader != null) reader.Close();
if (conn != null) conn.Close();
}
return null;
}
Correct me if I'm wrong, but it looks as though you're attempting to retrieve a row where you have a known MemberID. If that's the case, then you can always do something like this
int memberID = [some number];
DataTable results = new DataTable(); //Your SQL row will be "saved" in here
string command = string.Format("select * from MemberDetails where MemberID = {0}", memberID);
using (SqlDataAdapter sda = new SqlDataAdapter(command, con))
{
sda.Fill(results); //Your DataTable now has your values
}
All you need is something where you can feed the memberID to your condition variable.

Implement search / lookup in Win Form

I have a 4 text boxes on a win form. [First Name, Last Name, Job, Description.]
I have one table.
I have the dataset and a data table configured and I can navigate the records.
I want to know how can I search based on first name, obtain the data from dataset/table and display the info based on what is in the text box.
how do I do this such as, obtain the row, "inc" where the
txtFirstName = ds.Tables[0].Column[1]
Then I can:
DataRow row = ds.Tables[0].Rows[inc];
txtFirstName.Text = row[1];
txtSurname.Text = row[2];
txtJobTitle.Text = row[3];
txtDepartment.Text = row[4];
sorry, found the solution.
First I created a search method which returned the row...
private int first_name_search(string fname)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if ((string)ds.Tables[0].Rows[i]["first_name"] == fname)
{
send = i;
//result stuff
break;
}
}
// return result;
return send;
}
I used this method in the Search button click method and displayed the data...
In a function that return a string[]:
string[number_of_infos] infos = null;
connection = new SqlConnection(connectionString);
connection.Open();
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM your_table WHERE first_name = " + your_first_name;
cmd.Connection = connection;
rdr = cmd.ExecuteReader();
if(rdr.Read())
{
infos[0] = rdr["Surname"].ToString();
infos[1] = rdr["JobTitle"].ToString();
infos[2] = rdr["Department"].ToString();
}
cmd.Dispose();
connection.Close();
return infos;
Direct in your form:
connection = new SqlConnection(connectionString);
connection.Open();
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM your_table WHERE first_name = " + your_first_name;
cmd.Connection = connection;
rdr = cmd.ExecuteReader();
if(rdr.Read())
{
txtSurname.Text = rdr["Surname"].ToString();
txtJobTitle.Text = rdr["JobTitle"].ToString();
txtDepartment.Text = rdr["Department"].ToString();
}
cmd.Dispose();
connection.Close();
return infos;
Else if you want to get the row infos:
foreach(DataGridViewRow row in your_DGV.Rows)
if(row["FirstName"].Value.ToString() == txtFirstName.Text)
{
txtSurname.Text = row["Surname"].Value.ToString();
txtJobTitle.Text = row["JobTitle"].Value.ToString();
txtDepartment.Text = row["Department"].Value.ToString();
break;
}
FYI, you can use LINQ extensions to do this:
var tbl = ds.Tables[0].AsEnumerable();
return tbl.Where(p => p["first_name"] == fname).FirstOrDefault();
Edit: To select all matching rows from the DataTable:
var results = from row in tbl.AsEnumerable()
where row["first_name"] == fname
select row;

Categories

Resources