asp.net web api with Mysql database - c#

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

Related

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.

Creating Json string in C# with column headings

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

How to read data in each row and each column from sql table in asp.net using C#?

Sql database is StudentInfo and Table name is Registration
ID----------Name---------------Email---------------------------PhoneNo
1 Munasunghe amilamunasinghe#yahoo.com 0717069425
2 Liyanarachchi hareshliya6#gmail.com 0756706352
protected void Page_Load(object sender, EventArgs e)
{
string query = "select ID, Name, Email, PhoneNo from Registration";
SqlCommand cmd1 = new SqlCommand(query);
DataTable dt1 = GetData(cmd1);
int rowcount = dt1.Rows.Count;
/* I want to read data in each row step by step and assign to variables*/
}
The function GetData is used to get data from the Database.
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
ID is Primarykey.
Results should be like(Name,Email,Phone No are variables and 1,2,... are ID value)
Name[1]=Munasunghe
Name[2]=Liyanarachchi
Email[1]=amilamunasinghe#yahoo.com
Email[2]=hareshliya6#gmail.com
Phone No[1]=0717069425
Phone No[2]=0756706352
I would say you firstly create a new class for storing your data (like StudentInfo)
public class StudentInfo
{
public StudentInfo(int ID, string Name, string Email, string PhoneNo)
{
this.ID = ID;
this.Name = Name;
this.Email = Email;
this.PhoneNo = PhoneNo;
}
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string PhoneNo { get; set; }
}
Then use this function that return's a List of StudentInfo class
public List<StudentInfo> GetData()
{
List<StudentInfo> data = new List<StudentInfo>();
SqlConnection con = new SqlConnection("Your connection string");
SqlCommand command = new SqlCommand("SELECT * FROM [Registration]", con);
con.Open();
SqlDataReader sdr = command.ExecuteReader();
while(sdr.Read())
{
data.Add((int)sdr["ID"], (string)sdr["Name"], (string)sdr["Email"], (string)sdr["PhoneNo"]);
}
con.Close();
return data;
}
Then you use it like this:
List<StudentInfo> info = GetData();
foreach(StudentInfo si in info)
{
Response.Write("<h3>ID is " + si.ID + "</h3><p>StudentName is " + si.Name + "</p>");
}
To update the values do this:
public void SetValue(int StudentID, String NewName, String NewEmail, String NewPhone)
{
SqlConnection con = new SqlConnection("Your connection string");
SqlCommand command = new SqlCommand("UPDATE [Registration] SET [Name]='" + NewName + "', [Email]='" + NewEmail + "', [PhoneNo]='" + NewPhone + "' WHERE [ID]=" + StudentID + "", con);
con.Open();
command.ExecuteNonQuery();
con.close();
}
And I would suggest you to read some articles about sql

Provider & query

I want to create a C # application that can create and populate a DataTable.
Here is my code:
public DataTable GetData(string query)
{
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient");
using (DbConnection conn = factory.CreateConnection())
{
try
{
DbConnectionStringBuilder csb = factory.CreateConnectionStringBuilder();
csb["Data Source"] = #"";
csb["User Id"] = #"";
csb["Password"] = #"";
conn.ConnectionString = csb.ConnectionString;
conn.Open();
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = query;
using (DataTable dt = new DataTable())
{
DbDataAdapter da = factory.CreateDataAdapter();
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(dt);
return dt;
}
}
}
catch (Exception ex)
{
throw new Exception("Error", ex);
}
finally
{
if (conn.State != ConnectionState.Closed)
conn.Close();
}
}
}
In a second time, I have a class containing my various queries.
public class Query
{
public string SQL;
public string query1()
{
this.SQL = "select * from table1"
return this.SQL;
}
public string query2(string param)
{
this.SQL = "select * from table1 where id = '" + param + "' ";
return this.SQL;
}
I wish I could go query1 and / or query2 as parameter of my method GetData.
public DataTable GetData(query1)
{
//...
}
But I do not know how!
Thank you in advance for your help!

Updating multiple tables using SqlDataAdapter

I've been trawling through pages and pages on the internet for days now trying different approaches and I'm still not sure how I should be doing this.
On my third InsertCommand, I'd like to reference a column on the other 2 tables.
// Populate a DataSet from multiple Tables... Works fine
sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = new SqlCommand("SELECT * FROM hardware", sqlConn);
sqlDA.Fill(ds, "Hardware");
sqlDA.SelectCommand.CommandText = "SELECT * FROM software";
sqlDA.Fill(ds, "Software");
sqlDA.SelectCommand.CommandText = "SELECT * FROM join_hardware_software";
sqlDA.Fill(ds, "HS Join");
// After DataSet has been changed, perform an Insert on relevant tables...
updatedDs = ds.GetChanges();
SqlCommand DAInsertCommand = new SqlCommand();
DAInsertCommand.CommandText = "INSERT INTO hardware (host, model, serial) VALUES (#host, #model, #serial)";
DAInsertCommand.Parameters.AddWithValue("#host", null).SourceColumn = "host";
DAInsertCommand.Parameters.AddWithValue("#model", null).SourceColumn = "model";
DAInsertCommand.Parameters.AddWithValue("#serial", null).SourceColumn = "serial";
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "Hardware"); // Works Fine
DAInsertCommand.Parameters.Clear(); // Clear parameters set above
DAInsertCommand.CommandText = "INSERT INTO software (description) VALUES (#software)";
DAInsertCommand.Parameters.AddWithValue("#software", null).SourceColumn = "description";
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "Software"); // Works Fine
DAInsertCommand.Parameters.Clear(); // Clear parameters set above
DAInsertCommand.CommandText = "INSERT INTO join_hardware_software (hardware_id, software_id) VALUES (#hardware_id, #software_id)";
// *****
DAInsertCommand.Parameters.AddWithValue("#hardware_id", null).SourceColumn = "?"; // I want to set this to be set to my 'hardware' table to the 'id' column.
DAInsertCommand.Parameters.AddWithValue("#software_id", null).SourceColumn = "?"; // I want to set this to be set to my 'software' table to the 'id' column.
// *****
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "HS Join");
Could somebody please tell me where I am going wrong and how I could potentially overcome this? Many thanks! :)
With regards to your comments this seems to be one of those occasions where if you and I were sat next to each other we'd get this sorted but it's a bit tricky.
This is code I've used when working with SqlConnection and SqlCommand. There might be stuff here that would help you.
public static void RunSqlCommandText(string connectionString, string commandText) {
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = conn.CreateCommand();
try {
comm.CommandType = CommandType.Text;
comm.CommandText = commandText;
comm.Connection = conn;
conn.Open();
comm.ExecuteNonQuery();
} catch (Exception ex) {
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = "data access class";
el.WriteEntry(ex.Message + ex.StackTrace + " SQL '" + commandText + "'");
} finally {
conn.Close();
comm.Dispose();
}
}
public static int RunSqlAndReturnId(string connectionString, string commandText) {
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = conn.CreateCommand();
int id = -1;
try {
comm.CommandType = CommandType.Text;
comm.CommandText = commandText;
comm.Connection = conn;
conn.Open();
var returnvalue = comm.ExecuteScalar();
if (returnvalue != null) {
id = (int)returnvalue;
}
} catch (Exception ex) {
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = "data access class";
el.WriteEntry(ex.Message + ex.StackTrace + " SQL '" + commandText + "'");
} finally {
conn.Close();
comm.Dispose();
}
return id;
}

Categories

Resources