Fetch all needed data from 2 different databases - c#

[UPDATED]
I got a situation here where I need to fetch data from 2 different databases and then combine it into a model. I have an API method I made here that takes care of that but the moment I started working with a second database I got really confused on how I can retrieve more than one item. I'll explain. Here is the code to that method:
private List<FidelityModel> models;
public List<FidelityModel> getFidelityInfo2(string jobID) {
FidelityModel fidelityInfo;
SqlCommand command;
SqlConnection conn;
SqlDataReader reader;
string cjsJobName, ipwNumber, overnight, site;
int packageCount;
DateTime sla;
models = new List<FidelityModel>();
using (conn = new SqlConnection(#"server = [servername]; database = Dropoff; Integrated Security = true;")) {
conn.Open();
command = new SqlCommand("SELECT " +
"[Job Name], " +
"[Job ID], " +
"[Package Count], " +
"[Ship Method] " +
"FROM [cjs_data] " +
"WHERE [File Name] LIKE '%FDY%' AND [JOB ID] = #jobID", conn);
command.Parameters.Add("#jobID", SqlDbType.VarChar);
command.Parameters["#jobID"].Value = jobID;
//restructure to assign search results to string to later assign to model, as we will search again for SLA in a different database
using (reader = command.ExecuteReader()) {
if (reader.HasRows) {
while (reader.Read()) {
fidelityInfo = new FidelityModel();
fidelityInfo.cjsJobName = reader.GetString(0);
fidelityInfo.ipwNumber = reader.GetString(1);
fidelityInfo.packageCount = reader.GetInt32(2);
if (fidelityInfo.cjsJobName.Contains("OVN")) { fidelityInfo.overnight = "Yes"; } else {
fidelityInfo.overnight = (reader.GetString(3).Equals("Overnight")) ? "Yes" : "No";
}
//site = (cjsJobName.Contains("EDG")) ? "EDGEWOOD" : "Other Site"; //not always the case
fidelityInfo.site = "EDGEWOOD";
models.Add(fidelityInfo);
}
}
}
}
//How to incorporate this following block of code into the same model?
using (conn = new SqlConnection(#"server = [servername]; database = MustMail; Integrated Security = true;")) {
conn.Open();
command = new SqlCommand("SELECT [SLA] FROM [Job] WHERE [JobID] = #jobID", conn);
command.Parameters.Add("#jobID", SqlDbType.VarChar);
command.Parameters["#jobID"].Value = jobID;
using (reader = command.ExecuteReader()) {
if (reader.HasRows) {
while (reader.Read()) {
//fidelityInfo.sla = reader.GetDateTime(0);
}
}
}
}
return models;
}
As you can see right now I just have it working without fetching the SLA because I have no idea how to actually add the result I am fetching from the second database to the same model.

For each row in the DataReader create a new FidelityModel and add it to the list. Something like:
while (reader.Read())
{
var m = new FidelityModel()
{
cjsJobName = reader.GetString(0),
ipwNumber = reader.GetString(1),
packageCount = reader.GetInt32(2),
sla = DateTime.Now
};
if (m.cjsJobName.Contains("OVN"))
{
m.overnight = "Yes";
}
else
{
m.overnight = (reader.GetString(3).Equals("Overnight")) ? "Yes" : "No";
}
models.Add(m);
}

Related

How to query specific column in a UWP application?

I need to create a login that displays user data after login in a gridview / datatable
I'm able to display the username / password but not the user ID that's needed.
I've also tried creating a class where the values gets stored after login
private bool DataValidation(string user, string pass)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
using (MySqlCommand cmd = new MySqlCommand("SELECT * "+
"FROM member " +
"WHERE username=#user AND password=#pass;", conn))
{
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
cmd.Connection = conn;
cmd.Connection.Open();
MySqlDataReader login = cmd.ExecuteReader();
List<Connect> connectList = new List<Connect>();
while (login.Read())
{
Connect connect = new Connect();
connect.username = login.GetString(0);
connect.password = login.GetString(1);
connect.userID = login.GetString(4);
connectList.Add(connect);
}
if(connectList.Count > 0)
{
return true;
}
else
{
return false;
}
}
I'm mostly not sure how to store or display the values after they have been queried
Based on our conversation in the comments, let's focus on this code:
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
conn.Close();
return true;
}
else
{
conn.Close();
return false;
}
The only thing we are doing here is finding out if login contains any rows. But we are not doing anything with those rows.
Let's try something like this instead:
MySqlDataReader login = cmd.ExecuteReader();
while (login.Read())
{
var something1 = login.GetString(0); // this will get the value of the first column
var something2 = login.GetString(1); // this will get the value of the second column
}
Or, if you are adding the results to an object:
MySqlDataReader login = cmd.ExecuteReader();
List<MyObject> myObjectList = new List<MyObject>;
while (login.Read())
{
MyObject myObject = new MyObject;
myObject.something1 = login.GetString(0); // this will get the value of the first column
myObject.something2 = login.GetString(1); // this will get the value of the first column
myObjectList.Add(myObject);
}
if (myObjectList.Count > 0)
{
return true;
}
else
{
return false;
}
You will need to adjust to meet your needs, but hopefully, this will get you there.
More info here: SqlDataReader.Read Method

c# Using Two MysqlReaders

I want to retrive data from two differentables in my mysql data base so i created one connection and two readers, The second reader is not returning any results but the first reader is.
public List<BlogContentItemClass> BCITLIST = new List<BlogContentItemClass>();
// GET: api/BlogContents
[HttpGet]
public List<BlogContentItemClass> Get(string id)
{
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "SELECT * FROM test.blogtable where `id` = '" + id + "' ";
MySqlCommand cmd = new MySqlCommand(Query, conn);
MySqlDataReader MSQLRD = cmd.ExecuteReader();
BlogContentItemClass BCIT = new BlogContentItemClass();
Label BLOGID = new Label();
if (MSQLRD.HasRows)
{
while (MSQLRD.Read())
{
string TC = (MSQLRD["Topic"].ToString());
string CT = (MSQLRD["Category"].ToString());
string SM = (MSQLRD["Summary"].ToString());
string BID = (MSQLRD["id"].ToString());
BCIT.TopicSaved1 = TC;
BCIT.CategoriesSaved1 = CT;
BCIT.SummarySaved1 = SM;
BLOGID.Text = BID;
BCIT.TotalBodyStackLayout1.Add("Hello");
}
}
BCITLIST.Add(BCIT);
MSQLRD.Close();
string Query1 = "SELECT * FROM test.blogbodytable where `BlogID` = '" + BLOGID.Text + "' ";
MySqlCommand cmd1 = new MySqlCommand(Query1, conn);
MySqlDataReader MSQLRD1 = cmd1.ExecuteReader();
if (MSQLRD1.HasRows)
{
while (MSQLRD1.Read())
{
string BLOGBODY ;
BLOGBODY = (MSQLRD1["BlogBody"].ToString());
BCIT.TotalBodyStackLayout1.Add(BLOGBODY);
}
}
BCITLIST.Add(BCIT);
conn.Close();
return BCITLIST;
}
from my code the line BCIT.TotalBodyStackLayout1.Add("Hello"); in the first reader does add "hello" to the BCIT.TotalBodyStacklayout1, but the line BCIT.TotalBodyStackLayout1.Add( BLOGBODY); does not work, what am i doing wrong?
Can you be more specific what you mean by 'BCIT.TotalBodyStackLayout1.Add(BLOGBODY);' does not work. Are you getting any exception? or if BLOGBODY coming empty? There are few primitive troubleshooting steps you can perform to nail-down the issue
confirm what BLOGID.Text you are getting from your previous query and corresponding data is available in test.blogbodytable for that id.
if (MSQLRD1.HasRows) is resolving to true
Were you able to get inside while (MSQLRD1.Read())

how to create an id to be shown in the text box based on selected dropdownlist

i would like to create an id generator based on their department selected from the dropdownlist. lets say my ddl has 3 departments (A,B,C) and when generating an id it will be A20181001 and then A20181002 upon submission but when i pick B from the ddl after sending A20181001 to the database, it will be B20181001.
so far i have created the code for the increment for the id without the departments. here is the code i did so far. (I used the date for today so the 20181001 is just an example):
void getMRF_No()
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
int mrf = 0;
int i;
string a;
//string x = Request.QueryString["BUnit"];
string mrfNo = "";
database db = new database();
string conn = dbe.BU();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand cmd = connUser.CreateCommand();
SqlDataReader sdr = null;
string query = "SELECT TOP 1 MRF_NO FROM incMRF ORDER BY MRF_NO DESC";
connUser.Open();
cmd.CommandText = query;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr.GetInt32(0).ToString();
}
if (mrfNo == "")
{
mrfNo = Convert.ToString(year) + "" + 00;
}
mrf += 0;
i = Convert.ToInt32(mrfNo) + 1;
a = i.ToString();
txtMRFNo.Text = a;
connUser.Close();
}
any help to improve this code will be helpful. thank you :)
EDIT:
here is the dropdown list code:
void SelectBU()
{
string database = dbe.BU ();
using (SqlConnection con = new SqlConnection(database))
{
con.Open();
string query = "select BUnit from BusinessUnit";
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
DataSet ds = new DataSet();
sda.Fill(ds, "BUnit");
ddlBu.DataSource = ds;
ddlBu.DataTextField = "BUnit";
ddlBu.DataValueField = "BUnit";
ddlBu.DataBind();
selectOption(ddlBu, "Select Dept");
}
con.Close();
}
}
EDIT2: I will state what im searching for here incase some doesnt know or understand. What i want is upon selecting a department from a dropdownlist, for example i picked A. the textbox show show A2018102201. if i select B it should show B2018102201 and if its C then c2018102201. and it will change its number once i submit it to a database and a new form loads. So if A2018102201 is already in the database, then the text shown in the text box will be A2018102202. BUT if i select B then the textbox will show B2018102201 since it does not exist in the database yet.
First you should get max ID, then increase the numeric part of your Id, and If this is a multi-user application, you have to lock your table, because it might create many ID duplication, Therefore I'm not recommend to create ID like this on c#, it is better to create a Sequence on SQL server. but I wrote this sample for you, just call it with proper value.
static string getMRF_No(string prefixCharFromDropDownList)
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
string mrfNo = "";
SqlConnection connUser = new SqlConnection("Server=130.185.76.162;Database=StackOverflow;UID=sa;PWD=$1#mssqlICW;connect timeout=10000");
SqlCommand cmd = new SqlCommand(
$"SELECT MAX(MRF_NO) as MaxID FROM incMRF where MRF_NO like '{prefixCharFromDropDownList}%'"
,connUser
);
connUser.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr["MaxID"].ToString();
}
if (mrfNo == "")
{
mrfNo = prefixCharFromDropDownList + year + "000";
}
else
{
mrfNo = prefixCharFromDropDownList + (long.Parse(mrfNo.Substring(1)) + 1).ToString().PadLeft(2);
}
sdr.Close();
cmd = new SqlCommand($"INSERT INTO incMRF (MRF_NO) values ('{mrfNo}')",connUser);
cmd.ExecuteNonQuery();
connUser.Close();
//txtMRFNo.Text = prefixCharFromDropDownList + i.ToString();
return mrfNo;
}
I call this method on a console application as test.
static void Main(string[] args)
{
// send dropdown (selected char) as prefix to method
var newAId = getMRF_No("A");
var newAnotherAId = getMRF_No("A");
var newBId = getMRF_No("B");
var newAnotherAId2 = getMRF_No("A");
Console.ReadKey();
}

If there is no row in database sum command return an error

An error is thrown when there is no data in data base while converting a string value into int.
try {
SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con);
string companya_credit_amount = null, comapnyb_credit_amount = null;
con.Open();
SqlDataReader drc = cmdc.ExecuteReader();
if (drc.HasRows)
{
while (drc.Read())
{
companya_credit_amount = drc[0].ToString();
}
drc.Close();
con.Close();
}
SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con);
con.Open();
SqlDataReader drcp = cmdcp.ExecuteReader();
if (drcp.HasRows)
{
while (drcp.Read())
{
companyb_credit_amount = drcp[0].ToString();
}
drcp.Close();
con.Close();
}
if (!Page.IsPostBack)
{
int companyA = 0,companyB=0;
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companya_credit_amount.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyb_credit_amount.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
If there is value its working fine.but when there is no value in data base there is an error msg.
System.FormatException: Input string was not in a correct format.
Use IsDBNull to check for null values
Create and destroy all your type instances that implement IDisposable in using blocks. This ensures that connections are always released and resources are cleaned up.
Do not use connections across a class. Create them when needed and then dispose of them. Sql Server will handle connection pooling.
Get the native types directly, not the string equivalent! See changes to GetInt32 instead of ToString on the data reader.
You should refactor this to use SqlParameter's and make the retrieval statement generic OR get both SUM values in 1 sql call.
There is an if (!Page.IsPostBack) statement, if none of this code does anything if it is a postback then check at the top of the page and do not execute the sql statements if it is a postback. Otherwise the code is making (possibly) expensive sql calls for no reason.
try
{
int companyA = 0,companyB=0;
using(var con = new SqlConnection("connectionStringHere"))
{
con.Open();
using(SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con))
using(SqlDataReader drc = cmdc.ExecuteReader())
{
if (drc.Read() && !drc.IsDBNull(0))
companyA = drc.GetInt32(0);
}
using(SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con))
using(SqlDataReader drcp = cmdcp.ExecuteReader())
{
if (drcp.Read() && !drcp.IsDBNull(0))
companyB = drcp.GetIn32(0);
}
}
// if you are not going to do anything with these values if its not a post back move the check to the top of the method
// and then do not execute anything if it is a postback
// ie: // if (Page.IsPostBack) return;
if (!Page.IsPostBack)
{
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companyA.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyB.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
Try to replace this
SELECT SUM(Credited_amount)
WITH
SELECT ISNULL(SUM(Credited_amount),0)
Also find one confusing code while converting Credited amount values
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
---------^^^^^
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
I don't know about your business requirement but What i think Instead of using credit_amount value companya_credit_amount should be use to show value for companyA variable right?
You should do 2 things:
string companya_credit_amount = "", comapnyb_credit_amount = "";
Before assigning the value to these string variable you should check for db null as following:
while (drc.Read())
{
companya_credit_amount = (drc[0] != DbNull.Value) ? drc[0].ToString() : "" ;
}
Similarely
while (drcp.Read())
{
companyb_credit_amount = (drcp[0] != DbNull.Value) ? drcp[0].ToString() : "";
}
Try it.
You need to initialize credit_amount to empty and check if db value is null as shown below:
try {
companya_credit_amount = string.Empty;
companyb_credit_amount = string.Empty;
SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con);
string companya_credit_amount = null, comapnyb_credit_amount = null;
con.Open();
SqlDataReader drc = cmd
c.ExecuteReader();
if (drc.HasRows)
{
while (drc.Read())
{
companya_credit_amount = drcp.IsDBNull(0)?string.Empty:Convert.ToString(drcp[0]);
}
drc.Close();
con.Close();
}
SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con);
con.Open();
SqlDataReader drcp = cmdcp.ExecuteReader();
if (drcp.HasRows)
{
while (drcp.Read())
{
companyb_credit_amount = drcp.IsDBNull(0)?string.Empty:Convert.ToString(drcp[0]);
}
drcp.Close();
con.Close();
}
if (!Page.IsPostBack)
{
int companyA = 0,companyB=0;
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companya_credit_amount.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyb_credit_amount.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }

Drop Down List Selected Item

I am trying to select a dynamic data from drop down list and view the details of selected items. I have no problem in populating the drop down list with data from database. However, when I selected some items, it does not shows up the detail.
In my presentation layer, when drop down list item is selected:
protected void ddlScheduleList_SelectedIndexChanged(object sender, EventArgs e)
{
string address = ddlScheduleList.SelectedItem.ToString();
Distribution scheduledIndv = new Distribution();
scheduledIndv = packBLL.getDistributionDetail(address);
if (scheduledIndv == null)
{
Console.Out.WriteLine("Null");
}
else
{
tbScheduleDate.Text = scheduledIndv.packingDate.ToString();
tbBeneficiary.Text = scheduledIndv.beneficiary;
}
}
In my business logic layer, I get the selected address and pass it to data access layer:
public Distribution getDistributionDetail(string address)
{
Distribution scheduledIndv = new Distribution();
return scheduledIndv.getDistributionDetail(address);
}
In my data access layer, I tested out the SQL statement already. It gives me what I wanted. But it just won't show up in web page.
public Distribution getDistributionDetail(string address)
{
Distribution distributionFound = null;
using (var connection = new SqlConnection(FoodBankDB.GetConnectionString())) // get your connection string from the other class here
{
SqlCommand command = new SqlCommand("SELECT d.packingDate, b.name FROM dbo.Distributions d " +
" INNER JOIN dbo.Beneficiaries b ON d.beneficiary = b.id " +
" WHERE b.addressLineOne = '" + address + "'", connection);
connection.Open();
using (var dr = command.ExecuteReader())
{
if (dr.Read())
{
DateTime packingDate = DateTime.Parse(dr["packingDate"].ToString());
string beneficiary = dr["beneficiary"].ToString();
distributionFound = new Distribution(packingDate, beneficiary);
}
}
}
return distributionFound;
}
And my execute Reader method in another separated class:
public static string connectionString = Properties.Settings.Default.connectionString;
public static string GetConnectionString()
{
return connectionString;
}
public static SqlDataReader executeReader(string query)
{
SqlDataReader result = null;
System.Diagnostics.Debug.WriteLine("FoodBankDB executeReader: " + query);
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
result = command.ExecuteReader();
connection.Close();
return result;
}
I wonder what went wrong. Is it about the (!IsPostBack) or?
Thanks in advance.
You found your mistake, but to avoid Sql Injection, modify your code like this:
SqlCommand command = new SqlCommand("SELECT d.packingDate, b.name FROM dbo.Distributions d " +
" INNER JOIN dbo.Beneficiaries b ON d.beneficiary = b.id " +
" WHERE b.addressLineOne = #address", connection);
command.Parameters.AddWithValue("#address", address);

Categories

Resources