Check whether a row already exist in MySQL database? - c#

I'm writing a function that connects to Oracle MySQL to check for a specific row but it doesn't seem to work ! Could some one tell me how can I check whether a row already exist in DB
private bool groupAlreadyHasAdmin(string grp) {
try
{
myConn.Open();
strCmd = "SELECT * FROM users WHERE usergroup=#groupname AND privelege=2 LIMIT 1";
MySqlCommand myCmd = new MySqlCommand(strCmd, myConn);
myCmd.Parameters.AddWithValue("groupname", grp);
if (myCmd.ExecuteNonQuery() > 0)
{
return true;
}
else
{
return false;
}
}
catch (Exception E) { MessageBox.Show(E.Message); }
return false;
}

The answers above are using ExecuteReader, and ExecuteNonQuery. You may just prefer to use a simple Exists query, and then do ExecuteScalar, to make things simple. You can use the following command in your case:
using (MySqlCommand cmd = new MySqlCommand()){
cmd.Connection = con;
cmd.CommandText = #"SELECT EXISTS(SELECT 1 FROM users WHERE usergroup=#groupname AND privelege=2 LIMIT 1)";
cmd.Parameters.AddWithValue("groupName", groupName);
var result = cmd.ExecuteScalar();
//result will be 1 if it exists, and 0 if it does not..
}

I finally found a workaround to this using these lines of code:
...
return myCmd.ExecuteReader().Read();
...

One possibility is that the correct English spelling is "privilege". Perhaps this query would work:
strCmd = "SELECT * FROM users WHERE usergroup=#groupname AND privilege=2 LIMIT 1";
Also, you can just do SELECT 1 instead of SELECT * -- no reason to bring back data you are not going to use.

Give it a try: Get the number of rows first.
...
return myCommand.ExecuteNonQuery() > 0;

Related

Filter duplicate name from database in C#

When a method is called, I want to return true if the name already exists, and false otherize. My sample code is below.
private bool NameDuplicate(string txt)
{
conn.Open();
com.Connection = conn;
com.CommandText = "select Cat_d from Category";
SqlDataReader dr = com.ExecuteReader();
bool found = false;
while (dr.Read())
{
if (txt == dr["Cat_d"].ToString())
{
found = true;
}
else
{
found = false;
}
}
conn.Close();
return found;
}
if (NameDuplicate(cat_txt))
{
MessageBox.Show("Already exist!");
}
Please help me explained.
Below is some code you can use to do this but I want to point out that Realistically you probably wouldn't bother doing this in c#. You would add a UNIQUE constraint/index or primary key in the db and just insert values from c#, handling the case where there is an exception because the value already exists. Implementing a uniqueness logic in c# when sqlserver has been capable of doing it forever really is "buying a dog and barking yourself"
private bool NameDuplicate(string txt)
{
using(var con = new SqlConnection(YOUR CONNECTION STRING HERE)
using(var com = new SqlCommand("select count(*) from Category where cat_d = #c", con){
con.Open();
com.Parameters.Add("#c", SqlDbType.VarChar, 999).Value = txt;
var o = com.ExecuteScalar();
con.Close(); //optional; dispose will do this too
return Convert.ToInt32(o) != 0;
}
}
if (NameDuplicate(cat_txt))
{
MessageBox.Show("Already exist!");
}
Always use using blocks to ensure db related resources are disposed of, and don't reuse them (it seems your connection and command are defined somewhere else and you keep them for a long time/reuse them?
To check for existence we can (simplistically) count the number of entries, executescalar it and check the returned number. It might be slightly faster to use an EXISTS query but I picked this route because it is easy to read and keeps the code simpler.
Here is a query you could use in place of the select count, to achieve the same effect. It would be highly beneficial to use it if the column you're searching isn't indexed because, as Aaron points out, there isn't any point in having sqlserver count all of an entire table when realistically it could stop as soon as it finds the value you're looking for and deliver the same answer:
SELECT CASE WHEN EXISTS(SELECT null FROM Category where cat_d = #c) THEN 1 ELSE 0 END

SELECT ##IDENTITY in Access always returning 0

I have been trying to find a solution to this problem but so far nothing worked.
private void Insert()
{
string ConnectionStringAccess = Provider=Microsoft.ACE.OLEDB.12.0;Data Source=###Jet OLEDB:Database Password=###;
string query2 = "Select ##Identity";
int id = -1;
string Query = "INSERT INTO tblTable (EmpNo, Name) VALUES (132, 'TestName');";
OleDbConnection con = new OleDbConnection(ConnectionStringAccess);
OleDbCommand cmd = new OleDbCommand(Query, con);
try
{
con.Open();
if (cmd.ExecuteNonQuery() == 1)//the insert succeded
{
cmd.CommandText = query2;
id = Convert.ToInt32(cmd.ExecuteScalar());
}
}
catch (Exception ex)
{
//log the ex
}
finally
{
con.Dispose();
con.Close();
}
}
Each time I use the above method I always get a return of 0 in "id". What am I doing wrong? I tried using a different connection string or another way to get latest identifier:
Provider=Microsoft.Jet.OLEDB.4.0;
SCOPE_IDENTITY()
but again nothing. The Access db is 2003 or older (not sure exactly).
The ms access db is 2003 or older (not sure exactly)
I was able to recreate your issue with an Access 97 database. SELECT ##IDENTITY worked correctly with an Access 2000 database file (even when run from the same OleDbCommand object as the INSERT), but it always returned zero when run against an Access 97 database.
It appears that you will need to upgrade your database file to a newer version if you want SELECT ##IDENTITY to work.
You are using the same command object for both the insert and retrieval of ##identity.
According to this article you should create a separate command object for retrieving the ##identity value:
http://support.microsoft.com/kb/815629
Also, just to verify, the table you are inserting to does have an auto increment column, is that correct? If not, ##identity would not return anything.
Create two different commands for your queries, execute non query then execute scalar. It will return the first column of the first row in the result set returned by the query and it should be the id you're looking for.
private void Insert()
{
string ConnectionStringAccess = Provider=Microsoft.ACE.OLEDB.12.0;Data Source=###Jet OLEDB:Database Password=###;
int id = -1;
string Query = "INSERT INTO tblTable (EmpNo, Name) VALUES (132, 'TestName')";
string Query2 = "SELECT ##Identity";
OleDbConnection con = new OleDbConnection(ConnectionStringAccess);
OleDbCommand cmd = new OleDbCommand(Query, con);
OleDbCommand cmd2 = new OleDbCommand(Query2, con);
try
{
con.Open();
cmd.ExecuteNonQuery();
id = (int)cmd2.ExecuteScalar();
}
catch (Exception ex)
{
//log the ex
}
finally
{
con.Dispose();
con.Close();
}
}
thanks for all the responses. I found out what the problem was. Apparently the access file is very old, 1997 to be exact and that was the problem. As soon as a tried a new access 2010 file it worked.
Thanks again
My soluce with my very older databases (VB6 and ACCESS)
With VB NET and before upgrade Database to 4.
'MyInsertCommand.CommandText = "Select ##Identity" Don't work with old Access database
MyInsertCommand.CommandText = "SELECT TOP 1 ME_idn FROM MESURE ORDER BY ME_idn Desc"
Dim MyInsertIdn As Integer = MyInsertCommand.ExecuteScalar()

How to get a new id when there is no records in database?

when I run this method GetNewID() it should return max Product_Id + 1 from database. So if the Max Product_Id in the database is 20 the next one should be 21.
That's working fine.
But what's not working is when there is no records in database and it's null. I've tried with a different select statement and some if-statements but didn't work. Do you have any ideas on how I can solve this problem? Thanks in advance.
public static int GetNewId()
{
string selectString = #"SELECT MAX(Product_Id) FROM Products";
try
{
newId= 0;
connection = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=DB;Integrated Security=SSPI;");
connection.Open();
SqlCommand cmdSelectLastId = new SqlCommand(selectString, connection);
newId = Convert.ToInt32(cmdSelectLastId.ExecuteScalar());
}
finally
{
if (connection != null)
{
connection.Close();
}
}
return newId + 1;
}
Make the query return zero instead of null when there are no records:
string selectString = #"SELECT ISNULL(MAX(Product_Id),0) FROM Products";
The simple answer is:
SELECT ISNULL(MAX(Product_Id), 0) FROM Products
However, the way in which you're implementing this is potentially fraught with danger. For example, have you considered two concurrent processes running through this code one immediately after the other, but before the record for the first has been inserted into the database?
Depending upon your database, you may be better off using an automatically generated ID, or a GUID.
SELECT COALESCE(MAX(Product_Id), 0) FROM Products
And you can add 1 within the query, too:
SELECT COALESCE(MAX(Product_Id), 0) +1 FROM Products

Issue with conducting SQL statement within ASP.Net C# code

doubles quotes dont work so you have to type 'some value' to actually do variable comparisons when doing direct execution of SQL statements.
Problem is that now when I execute the SQL statement from ASP.NET code I dont seem to be getting any readings...I am not even getting errors :S....
I HAVE tried executing the SQL statement on its own, and it does work.
public static string testExi(string localIncidentNum)
{
try
{
string query = "SELECT TOP 1 UniqueColID From DBNAME WHERE LocalIncidentNum = #localIncidentNum ORDER BY [version] DESC";
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(connectionStr);
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#localIncidentNum", localIncidentNum);
connection.Open();
SqlDataAdapter adp = new SqlDataAdapter(command);
adp.Fill(dt);
connection.Close();
command.Dispose();
connection.Dispose();
if (dt.Rows.Count != 0)
{
string UniqueColID = dt.Rows[0]["UniqueColID"].ToString();
return UniqueColID;
}
else
{
return null;
}
string some = dt.Rows[0]["UniqueColID"].ToString();
return some;
}
catch (Exception err)
{
Global.tmpmsg = " Updating follow up was not successful. " + err.ToString();
return null;
}
}
If I hardcode an incident value in the SELECT statement it works but if I hardcode the incident value in .addwithvalue, it doesn't work.
command.Parameters.AddWithValue("#localIncidentNum", "12-023696");
Double check your sql statement:
SELECT TOP 1 UniqueColID From WHERE LocalIncidentNum = #localIncidentNum ORDER BY [version] DESC
From Where?
Edit
In observance of your change, best to always be as accurate as possible when describing your problem. Leaving out something like the table name of a sql statement is very misleading.
Perhaps add a datatype to your command parameter. I believe that you are not getting anything because it may be timing out on the command.
command.Parameters.AddWithValue("#localIncidentNum", localIncidentNum);
command.Parameters[0].SqlDbType = SqlDbType.VarChar;
I found a similar problem here, also using Varchar:
AddWithValue without DBType causing queries to run slowly
I solved it. The problem was that I (for some reason) needed to put the full path of the table before the table name in sql code when executing it from C sharp file:
SELECT TOP 2 [DB name].[dbo]. [table name]

How to check if mysql table is empty?

How to check if my table is empty from C#?
I have something like:
public MySqlConnection con;
public MySqlCommand cmd;
con = new MySqlConnection(GetConnectionString());
con.Open();
cmd = new MySqlCommand("SELECT * FROM data;", con);
Or I don't need to call SELECT statement?
You can use COUNT(*) with no WHERE close and see if exactly how many rows exist with the result.
Or you can do a SELECT (id) FROM tablename with no WHERE clause and if no rows are returned then the table is empty.
I'll give you an example in C# good luck
public bool checkEmptyTable(){
try
{
MySql.Data.MySqlClient.MySqlCommand com = new MySql.Data.MySqlClient.MySqlCommand();
conn = new MySql.Data.MySqlClient.MySqlConnection("YOUR CONNECTION");
com.Connection = conn;
com.CommandText = "SELECT COUNT(*) from data";
int result = int.Parse(com.ExecuteScalar().ToString());
return result == 0; // if result equals zero, then the table is empty
}
finally
{
conn.Close();
}
}
If 'data' might be a big table you would be better with this (where pkdata is your primary key field)
SELECT COUNT(*) FROM data WHERE pkdata = (SELECT pkdata FROM data LIMIT 1);
This will run very quickly whether you have 0 rows in 'data' or millions of rows. Using SELECT with no WHERE or ORDER BY means it just pulls the first row available, LIMIT 1 stops it getting more than 1.
Maybe something to look for if you have a program that ran very quickly six months ago but now runs like a dog in treacle!
SELECT COUNT(*)
FROM table
WHERE `col_name` IS NOT NULL

Categories

Resources