I'm using the code below to grab a list of companies from my database and load them into a list view. It's working great.
conn.Open();
string pricesqry = "SELECT company, url FROM companies";
SqlCommand pricescmd = new SqlCommand(pricesqry, conn);
SqlDataReader pricesreader = pricescmd.ExecuteReader();
while (pricesreader.Read())
{
ListViewItem company = new ListViewItem(pricesreader["company"].ToString());
company.SubItems.Add(pricesreader["url"].ToString());
company.SubItems.Add("Blank for now..");
pricesList.Items.Add(company);
}
conn.Close();
However, if I wanted to alphabetize my list by company names, by changing my select query to this:
string pricesqry = "SELECT company, url FROM companies ORDER BY company";
No data is loaded into the listview. Remove the order by section and the data appears again. What am I doing wrong?
In case you might have NULL's in database it would be better to get the values from reader like this:
Assuming company and url is a string.
ListViewItem company = new ListViewItem(Convert.IsDBNull(pricesreader.GetOrdinal("company")) ? null : pricesreader.GetString(pricesreader.GetOrdinal("company")));
company.SubItems.Add(Convert.IsDBNull(pricesreader.GetOrdinal("url")) ? null : pricesreader.GetString(pricesreader.GetOrdinal("url")));
hope this helps.
Credit goes to Minitech.
My 'Company' column type was set to Text. Changed to varchar and it's now working as I expected.
Related
I insert a list of records into sql and I want the ID to correspond to only 1 specific name but in this case I want to make it so that if a name is used by 2 different ids I can forcefully override that id and change it's value to whichever ID has the lower number. I don't know if this is clear or not but I can give an example. I want it so that when the programme sees Adam also having NameID 2 it changes its ID to 1 . I am programming in c# but even pseudocode would help I am just struggling with incorporating c# logic and sql querys.
Records:
NameID:1
Name : Adam
NameID:2
Name: Adam
NameID:3
Name : Sarah
I tried to see if a primary key has been used and used a data reader to confirm if it has rows .Then I look to see if the name has also been used before with a select statement and data reader but I don't know how to go from there I am trying to understand how to query sql with csharp logic. If anyone could help me I would really appreciate it this concept has had me stuck quite a lot.
Well, we assume you have a primary key, but as suggested by others, such a opeeration would be better done in sql studio.
However, you can code this, and say somthing like this:
string strSQL =
$#"select firstName, count(*) as NameCount,
(SELECT MIN(t.Nameid) from People as T where t.Firstname = People.Firstname)
as LowNameID
FROM People
group by people.Firstname
having count(*) > 1";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
DataTable rstDuplicates = new DataTable();
rstDuplicates.Load(cmdSQL.ExecuteReader());
// process duplicates, set ones with higher number = same as lowest
cmdSQL.CommandText =
#"update People Set NameID = #NameID where FirstName = #FName
AND NameID <> #NameID";
cmdSQL.Parameters.Add("#NameID", SqlDbType.Int);
cmdSQL.Parameters.Add("#FName", SqlDbType.NVarChar);
foreach (DataRow OneName in rstDuplicates.Rows)
{
cmdSQL.Parameters["#NameID"].Value = OneName["LowNameID"];
cmdSQL.Parameters["#FName"].Value = OneName["FirstName"];
cmdSQL.ExecuteNonQuery();
}
}
}
I would consider fixing up this mess. I would suggest deleting the duplicated reocrds, and setup the code to NOT allow the same name (if that is your goal here). In other words, don't allow such additions if that is your goal in the first place.
How to display the unitfunction value from mysql database and my query is below ,i don't know its right or wrong.
Help me out.
string fundev = "select unitfunctioncode from channels where channel_no = " + Channelid;
MySqlCommand getfun = new MySqlCommand(fundev, Connection1);
Console.WriteLine(getfun);
MAKE ENTITY CONTEXT FIRST:
YourEntity db= new YourEntity();
LINQ:
Console.Write(db.channels.Where(x=>x.channel_no == Channelid).Select(y=>y.unitfunctioncode));
This is modal first approach create modal from database and call this linq in controller
I'm not sure about the specifics of MySqlCommand, but I would expect to see an execute on your getfun object.
I would do something like this:
MySqlDataReader rdr = getfun.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
rdr.Close();
This takes into account multiple rows returned. You can omit the while loop if you're sure you will have a single row returned.
In my database i have three tables. One For employs where i keep their names, ids, salary... In the second one named Project i keep id, location, name. in the third one named WorksOn i keep the id from employs and the id from project. In my Asp .Net web site in gridview i need to display the employee's name and the name of the project that he is working.
string connect =
WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(connect);
try
{
con.Open();
}
catch (Exception err)
{
string error = err.Message;
con.Close();
}
SqlCommand command = new SqlCommand();
command.Connection = con;
SqlDataReader reader;
command.CommandText = "SELECT * FROM WorksON ";
reader= command.ExecuteReader();
In data source in gridview if i choose to display the values from WorksOn table it shows the id from employs and the id from project but what i need is to show the names on the employs and project.
I know that i need to do something with dataset but i don't know who.
Your SQL command must JOIN the related tables. Something like:
SELECT * FROM WorksOn JOIN Employee on WorksOn.EmployeeId = Employee.Id
Note that you should not SELECT "*" (all columns). You should only SELECT those columns that are necessary to your data view for performance.
On your SQL command, you don't mention anything about Employs. You need to use a JOIN SQL command in order to get both the employee name and the company name.
And instead of using "SELECT * FROM...", consider using the columns name instead, because you're not trying to get all the columns display. And it will help us understand the name of the columns to further help you.
Use a JOIN query like this:
SELECT project.projectName, employee.Name
FROM (worksOn
INNER JOIN employee
ON (worksOn.employeeId = employee.employeeId))
INNER JOIN project
ON (project.projectId = employee.employeeId)
AND (worksOn.projectId = project.projectId)
I have this code where I put data to the DataTable from where I show everything on DataGridView.
But when I look it contains information which supposed to be in file but its repeated twice.
Code to retrieve data from mysql database:
MySqlDataAdapter mySqlDataAdapter;
DataSet DS0 = new DataSet();
DataTable DT0;
string gender;
private void Filter()
{
ViewG.DataSource = null;
ViewG.Rows.Clear();
command.CommandText = "SELECT * FROM `table2` WHERE s1q2 = #gender";
command.Parameters.Add("#gender", MySqlDbType.VarChar);
command.Parameters["#gender"].Value = gender;
DT0 = DS0.Tables.Add("1Filter");
mySqlDataAdapter = new MySqlDataAdapter(command.CommandText, connection);
connection.Open();
mySqlDataAdapter.SelectCommand = command;
mySqlDataAdapter.Fill(DS0.Tables["1Filter"]);
ViewG.DataSource = DS0.Tables["1Filter"];
connection.Close();
}
Initially, on the start it retrieves all information from the database code (SELECT * FROM table) and displays on the DataGridView. And it works fine, but when I try to use filters to retrieve only for example "Females" problem occurs.
For full data I use:
mySqlDataAdapter.Fill(DS0.Tables["Full"]);
ViewG.DataSource = DS0.Tables["Full"];
For Filtered data:
mySqlDataAdapter.Fill(DS0.Tables["1Filter"]);
ViewG.DataSource = DS0.Tables["1Filter"];
If I run query used for filter on the application startup it does not duplicate and show correctly.
EDIT: SOLVED
From the code posted here, gender string is not assigned any value. So, your query be applying any filter that you want.
Thanks for you effort I found where the problem was. I used temp table on MySql and for some reason server did not dropped this table after connection is closed. So on the new query it added same items on the same table....
Here in the code I am trying to retrieve information from a database and store it in a table. In query i have used a variable to specify a table, i am doing so because i want to use this single piece of code to retrieve information from various tables based on which table name the variable "a" contain but when i am executing this it's throwing me an exception. please help...
MyOleDbConnection.Open();
string a = "login";
string query = string.Format("select Email,Username,PhoneNo,Department from '{1}' where Email='{0}'", editrecordtextBox.Text,a);
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter();
da = new OleDbDataAdapter(query, MyOleDbConnection.vcon);
da.Fill(dt);
Note- this is just the part of the code, the exception is occuring in this code only.
Your code is in fact working correctly.
First of all, remove your single quotes around the table name. These mark a text, not an identifier or name.
I can imagine that login is a reseverd name you cannot use as plain text in your SQL. Depending on the database you can quote your tablename so it is recognizes as a name, not an reserved word.
For SQL-Server it would be done with [ and ]:
string query = string.Format("select Email,Username,PhoneNo,Department from [{1}] where Email='{0}'", editrecordtextBox.Text,a);
If you would give us your database, we could help.
the way that tested and Worked is something like Below as you see the Table Name is Variable Form i Make a query with concatenate 3 section together
string query = "SELECT TOP 1 * FROM M" + TableName.ToString() + " ORDER BY ID
DESC";