Recordset gives non distinct values - c#

I have a part of code, which returns non distinct values.
Is there anyway, I could use a distinct function to the same to get distinct values?
Code:
public static Recordset queryTestDirector(string projectName, string query)
{
Recordset result = null;
/*Connect to Test director and pull down all the currently listed QC numbers*/
TDConnection tdConnection;
tdConnection = new TDAPIOLELib.TDConnection();
tdConnection.InitConnection("http://***/qcbin/", "ABC", "");
tdConnection.ConnectProject(projectName, "qc_manager", "");
Command cmd;
cmd = tdConnection.Command as Command;
String qcIDQuery = query;
cmd.CommandText = qcIDQuery;
result = cmd.Execute() as Recordset;
tdConnection.Disconnect();
return result;
}
The problem is the result returned gives values:
A,A,A,A,B,C,D
I want only A,B,C,D
Please suggest.

Changing your query to
select distinct BG_USER_50 from BUG where BG_STATUS in ('In Progress','Fixed','Unit Testing','Ready For UAT') and BG_USER_50 is not null order by BG_BUG_ID desc
should solve your problem

Haven't tried it, but this might work. You'll first have to convert your recordset into a dataset
ds.Tables[0].DefaultView.ToTable(true,"BG_USER_50");
Here's a link explaining more
http://www.c-sharpcorner.com/blogs/230/how-to-get-disticnt-rows-from-a-dataset-or-datatable.aspx
How to select distinct rows in a datatable and store into an array

Thanks a lot guys for your inputs, which made me rethink the query.
Finally this query works:
queryString = "select BG_USER_50, count(*) from BUG where BG_STATUS in ('In Progress','Fixed','Unit Testing','Ready For UAT') and BG_USER_50 is not null group by BG_USER_50 order by 1 desc"
I just needed a Group by clause.

Related

How to get different rows from two tables in SQL Server

I'm trying to build a query that can give me the different rows between two tables.
Here is my code:
try
{
string searchquery = "SELECT* FROM NewList EXCEPT SELECT* FROM Restaurants UNION All";
SqlCommand searchcom = new SqlCommand(searchquery, connection);
SqlDataAdapter da = new SqlDataAdapter(searchcom);
DataSet ds = new DataSet();
connection.Open();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
connection.Close();
}
catch (Exception er)
{
Debug.WriteLine(er.Message);
return;
}
I get the following error:
Incorrect syntax near 'All'.
What is the correct way/syntax to use Union All in SqlCommand class? I've tried to put it it my query string in too many ways but it's giving me the same error every time. How can I implement it in my search query with correct syntax ?
Your query is incorrect from UNION ALL on.
You can try it like this:
string searchquery = "SELECT * FROM NewList UNION ALL SELECT * FROM Restaurants ";
However, you need to be aware that:
It does not remove duplicate rows between the various SELECT statements (all rows are returned)
Each SELECT statement within the UNION ALL must have the same number of columns in the result sets with similar data types
Read here for more details.
Updated
You should use EXCEPT instead of UNION ALL if you want to get rows in one table that are not present in the other one.
Select Checking.RestID, FROM
(SELECT RestID FROM NewList EXCEPT Select RestID from Restaurants) as Checking
LEFT JOIN NewList ON Checking.RestID = NewList.RestID
this worked, thanks to anyone !

C# MySQL Order By Returns -1

I'm trying to get the last row of a table using C# but it doesn't seem to be working, this is my code:
MySqlConnection cnnGetID = new MySqlConnection(Global.connectionString);
cmd = "SELECT ContactID FROM Contacten ORDER BY ContactID DESC LIMIT 1";
MySqlCommand cmdGetID = new MySqlCommand(cmd, cnnGetID);
cnnGetID.Open();
string contactID = cmdGetID.ExecuteNonQuery().ToString();
MessageBox.Show(contactID);
cnnGetID.Close();
The value this returns is -1 while it should be returning 59.
The strange thing is is that when I run this command in phpmyadmin I DO get 59.
Any ideas on why C# is not returning the correct value but phpmyadmin is?
EDIT: problem solved, should've uses ExecuteScalar(). Looks like I've been staring at my monitor for a bit too long...
You need to use ExecuteScalar instead of ExecuteNonQuery.
MySqlConnection cnnGetID = new MySqlConnection(Global.connectionString);
cmd = "SELECT ContactID FROM Contacten ORDER BY ContactID DESC LIMIT 1";
MySqlCommand cmdGetID = new MySqlCommand(cmd, cnnGetID);
cnnGetID.Open();
string contactID = cmdGetID.ExecuteScalar().ToString();
MessageBox.Show(contactID);
cnnGetID.Close();
This should resolve your issue.
The value this returns is -1 while it should be returning 59.
No, it's behaving exactly as documented by IDbCommand.ExecuteNonQuery:
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1.
You're using a SELECT statement - a query. So instead of executing ExecuteNonQuery, you should be using ExecuteQuery and iterating over the results, or ExecuteScalar, given that you know you'll have a single result:
string contactID = cmdGetID.ExecuteScalar().ToString();
you should use ExecuteScalar because you are returning value ExecuteNonQuery returns the number of rows affected by update delete or insert opeation
you can check this for more info
ExecuteNonQuery
Returns the number of rows affected.
ExecuteScalar
Executes the query, and returns the first column of the first row in
the result set returned by the query. Additional columns or rows are
ignored.
for more information you can check this The MySqlCommand Object
you can use query like this
MySqlConnection cnnGetID = new MySqlConnection(Global.connectionString);
cmd = "SELECT TOP 1 ContactID FROM Contacten ORDER BY ContactID";
MySqlCommand cmdGetID = new MySqlCommand(cmd, cnnGetID);
cnnGetID.Open();
string contactID = cmdGetID.ExecuteNonQuery().ToString();
MessageBox.Show(contactID);
cnnGetID.Close();

Checking and Saving/Loading from MySQL C#

I am making something that requires MySQL. I have the saving done from in-game, which is simply done by INSERT.
I have a column that will have a password in and I need to check if the inputted password matched any of the rows and then if it is, get all of the contents of the row then save it to variables.
Does anyone have an idea how to do this in C#?
//////////////////////////
I have found how to save and get the string, however it will only get 1 string at a time :(
MySql.Data.MySqlClient.MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM (player) WHERE (pass)";
command.ExecuteNonQuery();
command.CommandType = System.Data.CommandType.Text;
MySql.Data.MySqlClient.MySqlDataReader reader = command.ExecuteReader();
reader.Read();
ayy = reader.GetString(1);
print (ayy);
if(ayy == password){
//something
}
My best practice is to use MySQLDataAdapter to fill a DataTable. You can then iterate through the rows and try to match the password.
Something like this;
DataTable dt = new DataTable();
using(MySQLDataAdapter adapter = new MySQLDataAdaper(query, connection))
{
adapter.Fill(dt);
}
foreach(DataRow row in dt.Rows)
{
//Supposing you stored your password in a stringfield in your database
if((row.Field<String>("columnName").Equals("password"))
{
//Do something with it
}
}
I hope this compiles since I typed this from my phone. You can find a nice explanation and example here.
However, if you are needing data from a specific user, why not specificly ask it from the database? Your query would be like;
SELECT * FROM usercolumn WHERE user_id = input_id AND pass = input_pass
Since I suppose every user is unique, you will now get the data from the specific user, meaning you should not have to check for passwords anymore.
For the SQL statement, you should be able to search your database as follows and get only the entry you need back from it.
"SELECT * FROM table_name WHERE column_name LIKE input_string"
If input_string contains any of the special characters for SQL string comparison (% and _, I believe) you'll just have to escape them which can be done quite simply with regex. As I said in the comments, it's been a while since I've done SQL, but there's plenty of resources online for perfecting that query.
This should then return the entire row, and if I'm thinking correctly you should be able to then put the entire row into an array of objects all at once, or simply read them string by string and convert to values as needed using one of the Convert methods, as found here: http://msdn.microsoft.com/en-us/library/system.convert(v=vs.110).aspx
Edit as per Prix's comment: Data entered into the MySQL table should not need conversion.
Example to get an integer:
string x = [...];
[...]
var y = Convert.ToInt32(x);
If you're able to get them into object arrays, that works as well.
object[] obj = [...];
[...]
var x0 = Convert.To[...](obj[0]);
var x1 = Convert.To[...](obj[1]);
Etcetera.

Getting MySQL record count with C#

I would like to know how can I get record count of a query with C#.
Here is the code that I use..
MySqlDataReader recordset = null;
query = new MySqlCommand("SELECT * FROM test ORDER BY type_ID ASC", this.conn);
recordset = query.ExecuteReader();
while (recordset.Read())
{
result.Add(recordset["type_ID"].ToString());
}
return result;
I was using a SELECT COUNT(*) and expected an int to be returned. You may need this to get a usable value:
mysqlint = int.Parse(query.ExecuteScalar().ToString());
A couple of things...
The SQL statement you would use is:
SELECT COUNT(*) FROM test
However, when using the MySQL Connector/Net to connect to MySQL through C# there is some care to be given when handling query results.
For example, as cited in this question and on Microsoft Connect int.Parse("0") equivalently known as Int32.Parse("0") can throw a FormatException on some machines.
I have found that Convert.ToInt32 handles this case nicely.
So your code will be something like this:
using (var conn = new MySqlConnection(cs))
{
conn.Open();
using (var cmd = new MySqlCommand("SELECT COUNT(*) FROM test", conn))
{
int count = Convert.ToInt32(cmd.ExecuteScalar());
return count;
}
}
Remember to make use of using statements in order to ensure that the MySQL objects get disposed of properly.
You're adding a new element in result for each row. Depending on the type of result you should be able to do something like result.Count after the while loop completes.
You could run another query first to get the count :
query = new MySqlCommand("SELECT count(*) as theCount FROM test ORDER BY type_ID ASC", this.conn);
but in truth, you are probably best changing the problem so you wont need the count until after you have populated the list.

How can I create a LINQ-to-SQL statement when I have table name as string?

If I have the name of a database table like this:
string tableName = "Addresses";
string tableName = "Customers";
How can I construct a dynamic LINQ statement like this:
var items = from o in db.{tableName}
select o;
foreach (var item in items)
{
sb.Append(item.Id + Environment.NewLine);
}
I know I could do something like this:
IEnumerable<Customer> results = db.ExecuteQuery<Customer>
("SELECT contactname FROM customers WHERE city = {0}",
"London");
But in this instance I don't want strongly typed objects as my result, I just want a recordset to pick apart.
Answer:
Thanks Shalkalpesh, I took your advice and solved this by just avoiding LINQ altogether:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["main"].ToString();
conn.Open();
string sql = "SELECT * FROM " + tableName;
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataTable dtResult = new DataTable();
da.Fill(dtResult);
foreach (DataRow drRow in dtResult.Rows)
{
Console.WriteLine(drRow["Id"].ToString());
}
da.Dispose();
conn.Close();
conn.Dispose();
If you want the recordset, you can access the Connection property of the DataContext class (db variable in your context) and use it to execute regular query and get the result in either of DataTable or DataReader.
You can use the Dynamic Linq Query library (or D-Linq for short).
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
Sorry - I'm away from a dev machine at the moment, but would this help?
It seems to suggest you should use DynamicQuery ...
Another way - as was mentioned by
several commenters in my previous post
- is to use DynamicQuery. DynamicQuery is one of the samples installed with
the 101 LINQ samples and you can find
it by clicking on Help | Samples in
Visual Studio. If you drill into the
sample folders there's a DynamicQuery
sample project, which basically
consists of a class that provides
string based lambda expression
parsing.
The class DynamicQuery class is self
contained and you can simply add it to
your project. It provides additional
extension methods that let you use
string expressions for various of the
query methods including the .Where()
method (but unfortunately for the
above example not the .Single()
method). So with Dynamic Query the
above .Load() method can also be
written as follows:
There's an actual code example on the post, too...
LINQ to SQL is meant to be strongly typed so I don't think you can use LINQ to SQL to use dynamic table names unless you use ExecuteQuery
Thanks
I don't think Dynamic Linq is the solution here.
As far as I know, there is no solution to your problem.
Even with dynamic linq, the compiler would need to somehow figure out what table the string refers to at compile time to allow strong typing of its members.
For instance, let's say you have two tables:
Product {Id, Name, Value}
Customer {Id, Firstname, Surname, Address, Email, ...}
And you use Linq-to-SQL as your ORM:
var items = from p in MagicTableResolver("Product")
where p.Firstname // <-- How could intellisense allow this?
select p;
var items = from c in MagicTableResolver("Customer")
where c.Name // <-- It can't, it cannot be strongly typed
select c;
Building off of this and this, here's how to run some some LINQ commands on a string tablename. I haven't figured out how to get the query syntax working (like "FROM" and "SELECT"), but you can still get and insert rows.
Type tableType = Assembly.GetExecutingAssembly().GetType("NameSpace.TableName");
ITable itable = dbcontext.GetTable(tableType);
//prints contents of the table
foreach (object y in itable) {
string value = (string)y.GetType().GetProperty("ColumnName").GetValue(y, null);
Console.WriteLine(value);
}
//inserting into a table
dynamic tableClass = Activator.CreateInstance(tableType);
//Alternative to using tableType
dynamic tableClass = Activator.CreateInstance(null, "NameSpace.TableName").Unwrap();
tableClass.Word = userParameter;
itable.InsertOnSubmit(tableClass);
dbcontext.SubmitChanges();
//sql equivalent
dbcontext.ExecuteCommand("INSERT INTO [TableName]([ColumnName]) VALUES ({0})", userParameter);

Categories

Resources