How to Remove Duplicate OUTPUT in SQL? - c#

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

Related

SQL command returning null for value

I am previously only familiar with Linq and the like for data access. I am working on something now that requires me to use actual SQL commands on the back end to return a single value. My code compiles and runs, however it is returning null for a value that I know should be returning something besides an empty string...
Is my structure off on this? Or is something else missing?
Below is my code:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
Here is a picture of the result set of the table:
Open the connection.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open(); //<- This line here.
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
cmd.ExecuteScalar() is probably throwing an InvalidOperationException because you haven't opened the connection. The exception is being caught, outputted to the console, then the initial value of newSex is begin returned since the call to ExecuteScalar threw.
ID is a int or varchar?
If is int use:
cmd.Parameters.Add("#sex", SqlDbType.Int).Value = sex;
instead of:
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
P.S.
Query parameters and parameter add into cmd.Parameters is case sensitive.
Write
#sex
instead of
#Sex
Figured it out. Had to open the cmd and close it AFTER I set the newSex variable to the value being pulled.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #Sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.Connection = conn;
adapter.SelectCommand = cmd;
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
adapter.Fill(ds);
newSex = cmd.ExecuteScalar().ToString();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
}
Try this:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID" + sex;;
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}

C# How to sort combobox items by date

void Fillcombo()
{
cbxProducts.Text = "";
cbxProducts.Items.Clear();
string constring = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf\"; Integrated Security = True";
string Query = "SELECT Name FROM Products;";
SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString(myReader.GetOrdinal("Name"));
cbxProducts.Items.Add(sName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
What the database looks like
I can't figure out how to sort the items listed in the combobox by their date while just displaying their Name
void Fillcombo()
{
cbxProducts.Text = "";
cbxProducts.Items.Clear();
string constring = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf\"; Integrated Security = True";
string Query = "SELECT Name FROM Products ORDER BY EDate;";
SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString(myReader.GetOrdinal("Name"));
cbxProducts.Items.Add(sName);
cbxProducts.Sorted = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This fixed it for me
Sort the dates before adding them to the combobox. Using "ORDER BY", the content is sorted by the String representation.
Make sure to turn of auto sorting.
Source
public class YourObject : IComparable{
public YourObject(string name) {
Name = name;
}
public string Name { get; set; }
public override string ToString()
{
return GetHashCode().ToString() + "_" + Name;
}
#region IComparable Members
public int CompareTo(Object other)
{
return Comparer.Default.Compare(this.ToString(), other.ToString());
}
#endregion
}

Display mySql table in a label in C#

I'm trying to implement an application combine with mysql database. I want to show table1 like in a terminal view instead of displaying it in a datagrid view. I'm using the code below to connect and display from MySql Database:
string myConnection = "datasource=localhost;port=3306;username=root;password=";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = "Select * FROM database_name.table1";
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = command.ExecuteReader();
while (myReader.Read())
{
label1.Text = myReader[0].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
myConn.Close();
This code only execute the last value of the table. but, I want to display whole table plus I want it to show in a label. So that I can style it like a terminal view.
Any help on this would be great.
Thanks in Advanced!
I think MySqlDataReader.FieldCount Property will be useful.
Try this code:
string myConnection = "datasource=localhost;port=3306;username=root;password=";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = "Select * FROM database_name.table1";
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = command.ExecuteReader();
while (myReader.Read())
{
if(label1.Text.Length > 0)
label1.Text += Environment.NewLine;
for(int i=0; i<myReader.FieldCount; i++)
label1.Text += myReader[i].ToString() + " ";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
myConn.Close();
NOTE: It is recommeded to use using statement for mysqlconnection, mysqldatareader and mysqlcommand.
UPDATE (using StringBuilder as recommended by jmcilhinney):
// Method used to retrieve data from DB
string GetFormattedText()
{
string myConnection = "datasource=localhost;port=3306;username=root;password=";
using (MySqlConnection myConn = new MySqlConnection(myConnection))
{
myConn.Open();
using (MySqlCommand command = myConn.CreateCommand())
{
command.CommandText = "Select * FROM database_name.table1";
using (MySqlDataReader myReader = command.ExecuteReader())
{
try
{
StringBuilder sb = new StringBuilder();
while (myReader.Read())
{
if (sb.Length > 0)
sb.Append(Environment.NewLine);
for (int i = 0; i < myReader.FieldCount; i++)
sb.AppendFormat("{0} ", myReader[i]);
}
return sb.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
return string.Empty;
}
Usage:
label1.Text = GetFormattedText();

mySQL get all Same value in the List

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

How to display images from mysqldatabase using c# in WPF?

string constring = "server=localhost;uid=root;" + "pwd=12345;database=products;";
string query = "SELECT prd_items_image FROM products.prd_items where prd_items_id=5";
MySqlConnection condatabase = new MySqlConnection(constring);
MySqlCommand cmddatabase = new MySqlCommand(query, condatabase);
MySqlDataReader myreader;
try
{
condatabase.Open();
myreader = cmddatabase.ExecuteReader();
while (myreader.Read())
{
byte[] imgg = (byte[])(myreader["prd_items_image"]);
if (imgg == null)
box.Image = null;
else
{
MemoryStream mstream = new MemoryStream(imgg);
box.Image = System.Drawing.Image.FromStream(mstream);
}
}
I am getting error at if condition,
box.Image=null andbox.Image = System.Drawing.Image.FromStream(mstream);
In these two cases, I am getting error at Image.
So please check it once. If you have any other code ,provide me if required.

Categories

Resources