Select only Employees with the job title waiter - c#

I am using sql server 2012 and visual studio 2010 and what I have so far is a single table int the database and a small c# application that loads the employees into a datagridview
however what I want to do is select only employees with the job title 'Waiter'
So far i have written queries on adding records editing deleting and displaying the whole data.
So far I have managed to display the names only by reading a specified column:
private void LoadEmpName()
{
sc.Close();
try
{
sc.Open();
cmd.CommandText = "select * from myEmployees";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
lstNames.Items.Add(dr[1].ToString());
}
}
sc.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
Is it possible to change my existing code so that only employees that are listed as 'Waiter' are displayed (first name only) or will i have to write a totally different query?

You should add a where clause to your SQL query. I don't know your database structure, but something like;
cmd.CommandText = "select * from myEmployees where title='waiter'";
It is much more efficient to do your filtering in SQL rather than in C#.

If you have a column called "JobTitle" then your query would become:
"select * from myEmployees where JobTitle like '%waiter%'";
The "like" is the comparison operator and the "%" is a wildcard of any number of characters.
There are several ways you could go if you want queries for different things. The simplest is to simply create a new method that has the part time test in the query string:
"select * from myEmployees where PartTime = 1";
However, you will need a new query for each possible search the user could do and this would become inefficient to maintain.
As you are populating a data grid you should look at doing the filtering in the client. You bring all the data (using paging if you have a large amount) and then let the user decide what information they are interested in seeing by specifying their own filters.

select * from myEmployees where jobtitle='Waiter'

Discalimer: The OP asked "Is it possible to change my existing code so that only employees that are listed as 'Waiter' are displayed (first name only) or will i have to write a totally different query?"
So purely to answer that you don't 'have' to use a new query. You could place an if before you add like this(assuming your second column is 'job title'):
while (dr.Read())
{
if(dr[2].ToString().EqualsIgnoreCase("Waiter")){
lstNames.Items.Add(dr[1].ToString());
}
}
Although I would not recommend it.

you will have to change the query . It is better approach.
I liked #CrisF solution. just addition to it.
private void LoadEmpName()
{
try
{
sc.Open();
//it will return all employees containing word waiter in Column JobTitle.
cmd.CommandText = "select * from myEmployees where JobTitle like '%waiter%' ";
dr = cmd.ExecuteReader();
while (dr.Read())
{
lstNames.Items.Add(dr[1].ToString());
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sc.Close();
}
}

Related

Connecting different tables to different items in combo box in C#

Good afternoon all,
I was hoping someone can point me in the right direction with this. I am currently working on a project and I am using an Access file as a database. I am trying to figure out how to populate items in my combobox from the different tables I have inside of my access database. I am using C# and Access 2016. I have tried to use some other examples and found that I am not looking in the right direction.
Edit:
I may have been a bit vague in this question. I have around 7 tables all with different names "ESC,AJJH,etc." in a Access file and I need to have the table names populate my combobox so when the user selects the combo box they can manipulate the data that's within the selected table. I hope this is more clear, I apologize if not.
Thank you!
private void Form1_Load(object sender, EventArgs e)
{
using (var connection = new OleDbConnection())
{
connection.ConnectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\grosales\Documents\rhg\RHG\Used.accdb;Jet OLEDB:Database Password = MyDbPassword;";
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from Tables";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while(reader.Read())
{
schoolcombo.Items.Add(reader);
}
}
catch (Exception ex)
{
MessageBox.Show("Connection Failed\r\n\r\n" + ex.Message);
}
}
You can use DbConnection. GetSchema to get the list of tables.
display the list of tables in access database using c#
It is not so clear what you want. But supposing that your tables have the same kind of columns. You could make use of UNION statement:
string query = "select field1, field2 from Table1 UNION select field1, field2 from Table2"; //AND SO ON

Reading data from Database and then filter data on some condition in C#

My question is what is the best way to fetch data from SQL Server in Code Behind(Using Query) and then apply filtering on some parameters in Code Behind(C#)
Like I have to fetch data from SQL Server with Dynamic Query - [TableName] should be passed as per input
Select * From [TableName]
And then i want to apply filtering on the result like applying effective date filtering, isActive or anything..
string SqlString = "SELECT * FROM TableName;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
}
catch (SqlException se)
{
DBErLog.DbServLog(se, se.ToString());
}
finally
{
Conn.Close();
}
or i would use
DataSet ds = new DatSet()
sda.Fill(ds)
How to iterate to the resultset(DataTable/DataSet) and filter records if we did not know the Table Columns(Except Effective Date or IsActive column)
Then Create object and convert the object in XML form as a result.
Your help is much appreciated. Thanks in advance.
As #Steve mentioned in his comment, a good practice is to filter as much as you can inside your SQL query.
there are multiple ways to filter and manipulate your data using T-sql conditions (WHERE,GROUP BY, HAVING etc). SQL server is very efficient compared to the manipulations you can do inside your application. here is an interesting discussion about this topic: “Never do in code what you can get the SQL server to do well for you” - Is this a recipe for a bad design?
on the other hand, there are exceptional cases where using sql steatments will be a lost of resources and unnecessary. for example High Frequency GUI changes and updates, When you encounter a case like that, multiple queries against sql server probably will be a waste of resources, in that case one way to cope is to extract data from a datatable or some other object that is cached inside your program using Linq, Lambda expressions, binary search etc...It is important to note that as a programmer you should master and understand what is the most efficient way to manipulate data.
please see my comments/advises inside your code:
private void foo()
{
// add a much conditions as you can inside the query
// for example "SELECT * FROM TableName WHERE Col2 IS NOT NULL AND col2 LIKE '%jr%' AND col3 > 3 AND YEAR(col4) = 2017"...
string SqlString = "SELECT * FROM TableName";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
// you can add more conditions, filterring, sorting, grouping using LINQ or Lambda Expretions
// for example create new datatable based on condition
DataTable newDt = dt.AsEnumerable().Where(x => x.Field<int>("col3") > 3).Select(y => y).CopyToDataTable();
// use WriteToXml() method and save as xml file
string FilePath = #"C:\YOUR_FILE_PATH.xml";
// give name to the datatable, WriteToXml() can not create xml with null table name
newDt.TableName = "myTableName";
// save
newDt.WriteXml(FilePath);
}
catch (SqlException se)
{
DBErLog.DbServLog(se, se.ToString());
}
finally
{
Conn.Close();
}
}

c# - MySQL connector universal SELECT query method for mutliple tables

I'm trying to write a method that returns a list with every row that a select query returns. But anything I can find on this is based on a single table.
This is what I'm trying:
public List<string> Select(string querystring)
{
string query = "SELECT " + querystring;
List<string> results = new List<string>();
if (this.OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
// in here I don't want a to "hard code" every column
results.Add( "returned data" );
}
dataReader.Close();
this.CloseConnection();
return results;
}
else
{
return results;
}
}
Is this possible? Do I need to make a new method for every table?
Or should I maybe return a list of objects instead of strings?
I'm really having a brainfart here so any help is appreciated.
As I stated from my comment:
I'm not sure what you're trying to do exactly... it looks like you're hoping to put a rows and columns (your data set) into just rows (your list of string). How are you planning on using this data? It will not be very useable trying to use it in the manner it looks like you're attempting. You can reference your data readers columns by index, but again I'm not clear on what you're hoping to accomplish.
You can however do it by doing something like this:
while (reader.Read())
{
// for loop with a maximum iteration of the number of columns in the reader.
for (int i=0;i<reader.FieldCount;i++)
{
results.Add(reader[i].ToString());
}
}
but again, I don't think this will get you data in a useable manner.
I would recommend you to look into Dapper.NET or EF6 or nHibernate.

How to get error message when retriving data from db, but no values there

I am having one table say emp, in that i dont have any values. If i using this query "select * from emp" in the asp.net coding like below:
con.Open();
String str="select * from emp where empname='Abdul'";
cmd=new SqlCommand(str,con);
SqlDataReader dr=cmd.ExecuteReader();
while(dr.Read())
{
textBox1.text=dr[0].ToString();
textBox2.text=dr[0].ToString();
textBox3.text=dr[0].ToString();
}
con.Close();
In emp tables, i dont have any empname as abdul, When i am doing this it should show some errors, how to do it?
Do something like this:
if (dr == null || !dr.HasRows)
{
//NO record found
lblError.Text ="No Records Found!";
}
else
{
//Record Found SUCCESS!
while(dr.Read())
{
textBox1.text=dr[0].ToString();
textBox2.text=dr[0].ToString();
textBox3.text=dr[0].ToString();
}
}
Regards
No it does not show any error because you enter the while only if there are some results in the query.
I would use an if/else and if DataReader has no content because no results found, I would notify the user or show something in the UI, depends on the type of application and on your exact needs.
You could load your data from a SQLDataAdapter in to a DataSet and use the following:
if (DataSet.Tables[0].Rows.Count <=0)
{
}

Check if table exists in c#

I want to read data from a table whose name is supplied by a user. So before actually starting to read data, I want to check if the database exists or not.
I have seen several pieces of code on the NET which claim to do this. However, they all seem to be work only for SQL server, or for mysql, or some other implementation. Is there not a generic way to do this?
(I am already seperately checking if I can connect to the supplied database, so I'm fairly certain that a connection can be opened to the database.)
You cannot do this in a cross-database way. Generally DDL (that is, the code for creating tables, indexes and so on) is completely different from database to database and so the logic for checking whether tables exist is also different.
I would say the simplest answer, though, would simply be something like:
SELECT * FROM <table> WHERE 1 = 0
If that query gives an error, then the table doesn't exist. If it works (though it'll return 0 rows) then the table exists.
Be very careful with what you let the user input, though. What's to stop him from from specifying "sysusers" as the table name (in SQL Server, that'll be the list of all database users)
You can use the DbConnection.GetSchema family of methods to retreive metadata about the database. It will return a DataTable with schema objects. The exact object types and restriction values may vary from vendor to vendor, but I'm sure you can set up your check for a specific table in a way that will work in most databases.
Here's an example of using GetSchema that will print the name and owner of every table that is owned by "schema name" and called "table name". This is tested against oracle.
static void Main(string[] args)
{
string providerName = #"System.Data.OracleClient";
string connectionString = #"...";
DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
DataTable schemaDataTable = connection.GetSchema("Tables", new string[] { "schema name", "table name" });
foreach (DataColumn column in schemaDataTable.Columns)
{
Console.Write(column.ColumnName + "\t");
}
Console.WriteLine();
foreach (DataRow row in schemaDataTable.Rows)
{
foreach (object value in row.ItemArray)
{
Console.Write(value.ToString() + "\t");
}
Console.WriteLine();
}
}
}
That's like asking "is there a generic way to get related data" in databases. The answer is of course no - the only "generic way" is to have a data layer that hides the implementation details of your particular data source and queries it appropriately.
If you are really supporting and accessing many different types of databases without a Stategy design pattern or similar approach I would be quite surprised.
That being said, the best approach is something like this bit of code:
bool exists;
try
{
// ANSI SQL way. Works in PostgreSQL, MSSQL, MySQL.
var cmd = new OdbcCommand(
"select case when exists((select * from information_schema.tables where table_name = '" + tableName + "')) then 1 else 0 end");
exists = (int)cmd.ExecuteScalar() == 1;
}
catch
{
try
{
// Other RDBMS. Graceful degradation
exists = true;
var cmdOthers = new OdbcCommand("select 1 from " + tableName + " where 1 = 0");
cmdOthers.ExecuteNonQuery();
}
catch
{
exists = false;
}
}
Source: Check if a SQL table exists
You can do something like this:
string strCheck = "SHOW TABLES LIKE \'tableName\'";
cmd = new MySqlCommand(strCheck, connection);
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
cmd.Prepare();
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
Console.WriteLine("Table Exist!");
}
else (reader.HasRows)
{
Console.WriteLine("Table Exist!");
}

Categories