mySQL get all Same value in the List - c#

in my Database have 7 different of data. But in my Result all return the same value.
What logic error in my code??? which [0]-[6] is 1 result with same value.
The result like this [0] ="tester" [1]="tester" [2]="tester"....util [6]
public class StreamWcf : IStreamWcf
{
public List<streamData> getMusic()
{
try
{
MySqlConnection con = new MySqlConnection(WebConfigurationManager.ConnectionStrings["ComeVoxConnectionString"].ToString());
MySqlDataReader myReader;
streamData user_stream = new streamData();
List<streamData> userStream = new List<streamData>();
//string cmdText = "SELECT m.id, s.avatar, s.username, m.title, m.path, m.description, m.date FROM users s, musics m WHERE (musics.userID = users.id)";
string cmdText = "SELECT musics.id as MID, users.avatar as UserPic, users.username as userName, musics.title as MTitle, musics.path as MusicPath, musics.description as Mdesc, musics.date as MDate FROM `users`, `musics` WHERE musics.userID = users.id;";
con.Open();
MySqlCommand cmd = new MySqlCommand(cmdText, con);
myReader = cmd.ExecuteReader();
if (myReader.HasRows)
{
while (myReader.Read())
{
user_stream.musicID = Convert.ToInt32(myReader["MID"].ToString());
user_stream.Title = myReader["MTitle"].ToString();
user_stream.FilePath = myReader["MusicPath"].ToString();
user_stream.desc = myReader["Mdesc"].ToString();
user_stream.Artists = myReader["userName"].ToString();
user_stream.releaseDate = Convert.ToDateTime(myReader["MDate"].ToString());
user_stream.imgUrl = myReader["UserPic"].ToString();
userStream.Add(user_stream);
}
myReader.Close();
con.Close();
}
return userStream;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}

You're operating on one and the same user_stream instance. Move streamData user_stream = new streamData(); into your while loop to create a new one each iteration.

Create new user_stream in your while block.
And its' preferable to use using statements
using (var con =new MySqlConnection(WebConfigurationManager.ConnectionStrings["ComeVoxConnectionString"].ToString()))
{
var userStream = new List<streamData>();
//string cmdText = "SELECT m.id, s.avatar, s.username, m.title, m.path, m.description, m.date FROM users s, musics m WHERE (musics.userID = users.id)";
string cmdText =
"SELECT musics.id as MID, users.avatar as UserPic, users.username as userName, musics.title as MTitle, musics.path as MusicPath, musics.description as Mdesc, musics.date as MDate FROM `users`, `musics` WHERE musics.userID = users.id;";
con.Open();
using (var cmd = new MySqlCommand(cmdText, con))
{
using (MySqlDataReader myReader = cmd.ExecuteReader())
{
if (myReader.HasRows)
{
while (myReader.Read())
{
var user_stream = new streamData();
user_stream.musicID = Convert.ToInt32(myReader["MID"].ToString());
user_stream.Title = myReader["MTitle"].ToString();
user_stream.FilePath = myReader["MusicPath"].ToString();
user_stream.desc = myReader["Mdesc"].ToString();
user_stream.Artists = myReader["userName"].ToString();
user_stream.releaseDate = Convert.ToDateTime(myReader["MDate"].ToString());
user_stream.imgUrl = myReader["UserPic"].ToString();
userStream.Add(user_stream);
}
}
}
}
}

Related

SQL commands not working in C# (ASP.NET web forms)

I'm having a trouble with my code.
I'm trying to have the user the ability to submit his email to subscribe to my "notify me" service, I havn't code anything lately so I a bit confused..
I'm trying to Insert, Read, and Update data in my Online SQL Server.. but nothing seems to work! I don't know why I tried everything I know I check a million times it seems good.
Plus if there is any errors my catch should show it to me but even that doesn't work :(
Take a look at this maybe your eyes will see something I don't see.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["notifyCS"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
try
{
string checkEmail = "SELECT User_Email FROM tbl_users WHERE User_Email = #User_Email";
string checkSubscription = "SELECT User_Status FROM tbl_users WHERE User_Email = #User_Email";
string submitEmail = "INSERT INTO tbl_users (User_UID, User_Email, User_Status) VALUES (#User_UID, #User_Email, #User_Status)";
string submitEmail2 = "UPDATE tbl_users SET User_UID = #User_UID, User_Status = #User_Status WHERE User_Email = #User_Email";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
SqlDataAdapter emailSDA = new SqlDataAdapter
{
SelectCommand = emailCMD
};
DataSet emailDS = new DataSet();
emailSDA.Fill(emailDS);
//if there is no email registered.
if (emailDS.Tables[0].Rows.Count == 0)
{
SqlCommand registerEmail = new SqlCommand(submitEmail, conn);
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail.ExecuteNonQuery();
registerEmail.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
else if (emailDS.Tables[0].Rows.Count > 0)
{
using (SqlCommand checkSub = new SqlCommand(checkSubscription, conn))
{
checkSub.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
SqlDataReader sdr = checkSub.ExecuteReader();
if (sdr.HasRows)
{
string res = sdr["User_Status"].ToString();
if (res != "subscribed")
{
using (SqlCommand registerEmail2 = new SqlCommand(submitEmail2, conn))
{
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail2.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail2.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail2.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail2.ExecuteNonQuery();
registerEmail2.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
}
else
{
conn.Close();
conn.Dispose();
Response.Redirect("index.aspx");
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
}
}
Try it this way:
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
string checkEmail = "SELECT * FROM tbl_users WHERE User_Email = #User";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
emailCMD.Parameters.Add("#User", SqlDbType.NVarChar).Value = email.Text;
SqlDataAdapter da = new SqlDataAdapter(emailCMD);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
DataTable emailRecs = new DataTable();
emailRecs.Load(emailCMD.ExecuteReader());
DataRow OneRec;
if (emailRecs.Rows.Count == 0)
{
OneRec = emailRecs.NewRow();
emailRecs.Rows.Add(OneRec);
}
else
{
// record exists
OneRec = emailRecs.Rows[0];
}
// modify reocrd
OneRec["User_UID"] = User_UID;
OneRec["User_Email"] = email.Text;
OneRec["User_Status"] = "subscribed";
email.Text = null;
da.Update(emailRecs);
}
}

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

How to Remove Duplicate OUTPUT in SQL?

I have a problem with a ComboBox, its items are being duplicated. How can I prevent this situation? Here is some images:
Here is my code sample used to populate it:
string SelectQuery = "SELECT Part , Model FROM ctautoparts.nissanpart , ctautoparts.nissan ;";
MySqlConnection sqlConn = new MySqlConnection(myConnectionString);
MySqlCommand cmdDatabase = new MySqlCommand(SelectQuery, sqlConn);
MySqlDataReader myReader;
try
{
sqlConn.Open();
myReader = cmdDatabase.ExecuteReader();
// int model = myReader.GetOrdinal("model");
//int model1 = myReader.GetOrdinal("part");
while (myReader.Read())
{
// string namethestore = myReader.IsDBNull(model)
// ? string.Empty
// : myReader.GetString("model");
// this.carmodel.Text = namethestore;
// string namethestore1 = myReader.IsDBNull(model)
// ? string.Empty
// : myReader.GetString("parts");
/// this.carpart.Text = namethestore1;
carmodel.Items.Add(myReader["Model"].ToString());
carpart.Items.Add(myReader["Part"].ToString());
}
}
catch (Exception msg)
{
MessageBox.Show(msg.Message);
}
Add distinct to your select query, so that the duplicates will be removed
It looks your query is returning duplicated lines. I'd suggest executing them separatedely:
try
{
// POPULATE MODELS
string modelsQuery = "SELECT Model FROM ctautoparts.nissan;";
using (MySqlConnection sqlConn = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmdDatabase = new MySqlCommand(modelsQuery, sqlConn))
{
sqlConn.Open();
MySqlDataReader myReader = cmdDatabase.ExecuteReader();
// int model = myReader.GetOrdinal("model");
//int model1 = myReader.GetOrdinal("part");
while (myReader.Read())
{
carmodel.Items.Add(myReader["Model"].ToString());
}
}
}
// POPULATE PARTS
string partsQuery = "SELECT Part FROM ctautoparts.nissanpart;";
using (MySqlConnection sqlConn = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmdDatabase = new MySqlCommand(partsQuery, sqlConn))
{
sqlConn.Open();
MySqlDataReader myReader = cmdDatabase.ExecuteReader();
// int model = myReader.GetOrdinal("model");
//int model1 = myReader.GetOrdinal("part");
while (myReader.Read())
{
carpart.Items.Add(myReader["Part"].ToString());
}
}
}
}
catch (Exception msg)
{
MessageBox.Show(msg.Message);
}

Using Prepare select statements in C#

I am having the below code where I am querying the MySQL database. I need to replace my select query to prepare statement
public static void ValidateName(List<Employees> EmpList, string Grp)
{
var connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string selectQuery;
for (int i = 0; i < EmpList.Count; i++)
{
selectQuery = "Select EmpName from Employee where group = #Grp AND #Name in (FirstName, LastName);";
using (MySqlConnection conn = new MySqlConnection(connStr))
using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn))
{
cmd.Parameters.Add("#Grp", MySqlDbType.VarChar).Value = Grp;
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = EmpList[i].Name;
conn.Open();
var reader = cmd.ExecuteReader();
List<string> lineList = new List<string>();
while (reader.Read())
{
lineList.Add(reader.GetString(0));
}
if (lineList.Count <=0)
{
WriteValidationFailure(EmpList[i], "Name doesnot exists in the DB");
}
conn.Close();
}
}
}
This code works perfectly. But for improvement I need to use the prepare statements instead of the query I am using. Because I am having similar kinds of various validation in my code, I am not sure how to reuse the parameters effectively.
You are very close. Just call cmd.Prepare(), keep references to the parameters, and reuse the command:
public static void ValidateName(List<Employees> EmpList, string Grp)
{
var connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string selectQuery;
selectQuery = "Select EmpName from Employee where group = #Grp AND #Name in (FirstName, LastName);";
using (MySqlConnection conn = new MySqlConnection(connStr)) {
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn))
{
var prmGrp = cmd.Parameters.Add("#Grp", MySqlDbType.VarChar);
var prmName = cmd.Parameters.Add("#Name", MySqlDbType.VarChar);
cmd.Prepare();
for (int i = 0; i < EmpList.Count; i++)
{
prmGrp.Value = Grp;
prmName.Value = EmpList[i].Name;
using (var reader = cmd.ExecuteReader()) {
List<string> lineList = new List<string>();
while (reader.Read())
{
lineList.Add(reader.GetString(0));
}
if (lineList.Count <=0)
{
WriteValidationFailure(EmpList[i], "Name doesnot exists in the DB");
}
}
}
}
conn.Close();
}
}

List is empty at the return statement MVC

I have a form where the user searched for a customer's account by name, ssn, old account number, etc. When I am populating the list in the while loop, the values are present, however when it exits the loop, in the return statement the count is 0. Any idea why I am loosing the values?
Function creating the list:
public static List<Account> GetAccountNumbersFromCustomerSSN(string CustomerSSN)
{
List<Account> accts = new List<Account>();
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TA_connectionstring"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("spGet_Account_Numbers_From_SSN", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlParameter P1 = new SqlParameter("#CUSTOMER_SSN", DbType.String);
P1 = new SqlParameter("#CUSTOMER_SSN", DbType.String);
P1.Value = CustomerSSN;
cmd.Parameters.Add(P1);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Account acct = new Account
{
OriginalAcctNumber = dr["TABOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
FTBOATAcctNumber = dr["FTBOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
SSN = CustomerSSN.Substring(CustomerSSN.Length -4).PadLeft(CustomerSSN.Length, '*'),
CustomerName = dr["CUST_NAME"].ToString(),
ProductType = dr["TRGT_PROD"].ToString()
};
}
con.Close();
}
}
catch (Exception ex)
{
ExceptionUtility.LogException(ex, "GetCustomerSSN()");
}
return accts;
}
You're not adding the acct to the list of Accounts.
while (dr.Read())
{
Account acct = new Account
{
OriginalAcctNumber = dr["TABOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
FTBOATAcctNumber = dr["FTBOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
SSN = CustomerSSN.Substring(CustomerSSN.Length -4).PadLeft(CustomerSSN.Length, '*'),
CustomerName = dr["CUST_NAME"].ToString(),
ProductType = dr["TRGT_PROD"].ToString()
};
accts.Add(acct); // You're missing this line.
}
You're not adding the acct to the accts list!
while (dr.Read())
{
Account acct = new Account
{
OriginalAcctNumber = dr["TABOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
FTBOATAcctNumber = dr["FTBOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
SSN = CustomerSSN.Substring(CustomerSSN.Length -4).PadLeft(CustomerSSN.Length, '*'),
CustomerName = dr["CUST_NAME"].ToString(),
ProductType = dr["TRGT_PROD"].ToString()
};
accts.Add(acct); // ADD THIS HERE
}
All depending on how you want to do it you can also return IEnumerable by:
public static IEnumerable<Account> GetAccountNumbersFromCustomerSSN
(string CustomerSSN)
{
List<Account> accts = new List<Account>();
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings
["TA_connectionstring"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("spGet_Account_Numbers_From_SSN", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlParameter P1 = new SqlParameter
("#CUSTOMER_SSN", DbType.String);
P1 = new SqlParameter
("#CUSTOMER_SSN", DbType.String);
P1.Value = CustomerSSN;
cmd.Parameters.Add(P1);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
yield return new Account
{
OriginalAcctNumber =
dr["TABOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
FTBOATAcctNumber =
dr["FTBOAT_ACCOUNT_NUMBER"].ToString().TrimStart('0'),
SSN =
CustomerSSN.Substring(CustomerSSN.Length -4).PadLeft(CustomerSSN.Length, '*'),
CustomerName =
dr["CUST_NAME"].ToString(),
ProductType =
dr["TRGT_PROD"].ToString()
};
}
con.Close();
}
}
catch (Exception ex)
{
ExceptionUtility.LogException(ex, "GetCustomerSSN()");
}
}

Categories

Resources