Solved

Return Multiple Columns on MySQL Queries

Posted on 2008-06-25
10
604 Views
Last Modified: 2010-04-21
I have a MySQL Connection that works, but I can only 1 column per query. Here is my Connection Class:

    class clsMySqlODBCConnection
    {
        public int QueryType = 0;
        public System.Data.Odbc.OdbcConnection OdbcCon;
        public System.Data.Odbc.OdbcCommand OdbcCom;
        public System.Data.Odbc.OdbcDataReader OdbcDR;
        public string ConStr;
        private string MySqlServer = "linux02", MySqlPort = "", MySqlDatabase = "EbtronSystems", MySqlUser = "ebtron", MySqlUserPass = "ebtron", MySqlOption = "3";

        public clsMySqlODBCConnection()
        {
            ConStr = "DRIVER={MySQL ODBC 3.51 Driver};SERVER=" + MySqlServer + ";PORT=" + MySqlPort + ";DATABASE=" + MySqlDatabase + ";UID=" + MySqlUser + ";PWD=" + MySqlUserPass + ";OPTION=" + MySqlOption + "";
            OdbcCon = new System.Data.Odbc.OdbcConnection(ConStr);
           
            try
            {
                //txtLog.AppendText("Openning connection...\r\n");
                if (OdbcCon.State == ConnectionState.Closed)
                {
                    OdbcCon.Open();
                }
                //txtLog.AppendText("Connection opened\r\n");
                //MessageBox.Show("Connection opened\r\n");
            }
            catch (System.Data.Odbc.OdbcException Ex)
            {
                //txtLog.AppendText(Ex.Message + "\r\n");
                //MessageBox.Show("Could not access the database.\r\nPlease make sure you completed the fields with the correct information and try again.\r\n\r\nMore details:\r\n" + Ex.Message, "Database connection error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void MySqlDisconnection()
        {
            if (OdbcCon.State == ConnectionState.Open)
            {
                OdbcCon.Close();
                //MessageBox.Show("Connected Closed\r\n");
            }
        }

        public string[] MySQLQuery(string qry, int fldidx)
        {
            List<string> list = new List<string>();

            string tStr = null;     // the following is not needed: = Convert.ToString(null);
            if (OdbcCon.State == ConnectionState.Open)
            {
                OdbcCom = new System.Data.Odbc.OdbcCommand(qry, OdbcCon);
                if (fldidx >= 0)
                {
                    OdbcDR = OdbcCom.ExecuteReader();
                    while (OdbcDR.Read())
                    {
                        tStr = Convert.ToString(OdbcDR[fldidx]);
                        list.Add(tStr);
                    }
                }
                else
                {
                    OdbcCom.ExecuteNonQuery();
                    QueryType = 1;
                }
            }
            return list.ToArray();
        }
        public void MySQLNONQuery(string qry)
        {
            if (OdbcCon.State == ConnectionState.Open)
            {
                OdbcCom = new System.Data.Odbc.OdbcCommand(qry, OdbcCon);
                OdbcCom.ExecuteNonQuery();
                QueryType = 1;
            }
        }

        public object InitializeCnnObject()
        {
            // Create and initilize a recordset to represent the User Table
            clsMySqlODBCConnection OpenConnection = new clsMySqlODBCConnection();
            return OpenConnection;
        }
    }
////////////////////


I run a query like this:

string[] strQryResults = null;

strQryResults = OpenConnection.MySQLQuery("SELECT * FROM AdvantageOrderForm WHERE ItemIndexNumber = '" + tmpItemIndexNumber + "'", 0);

I can return only one column I have to run another query in order to get another column:

strQryResults = OpenConnection.MySQLQuery("SELECT * FROM AdvantageOrderForm WHERE ItemIndexNumber = '" + tmpItemIndexNumber + "'", 1);

I have a table with more than 50 columns, it takes nearly a minute to run all those queries. I need to be able to run 1 query and be able to get results for all the columns.

I know this is all because of my function:
public string[] MySQLQuery(string qry, int fldidx)

But I'm pretty new to DotNet and also to C#, so I'm not sure how to make it work.

Thanks for any help
0
Comment
Question by:SaltyDawg
  • 6
  • 4
10 Comments
 
LVL 18

Expert Comment

by:jcoehoorn
ID: 21866845
You can only get one column because the clsMySqlODBCConnection class _that you wrote_ (.Net style guildelines recommend against prefixes like 'cls', by the way) only returns one column.  If you want more, make your data wrapper class return more.  All the columns are there in the data reader.
0
 
LVL 1

Author Comment

by:SaltyDawg
ID: 21866961
Wow, the prefix "cls" is not good. Never knew that. What would having the prefix do to hurt me?

How do I get the other columns from the data reader? Changes would I have to do to the wrapper
0
 
LVL 18

Accepted Solution

by:
jcoehoorn earned 500 total points
ID: 21867247
"cls" won't really hurt anything.  It's just no longer a recommended best practice:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconNETFrameworkDesignGuidelines.asp

As for fixing your wrapper, I'd just return the raw data reader, perhaps using a provider agnostic IDataReader to make it more flexible to database changes.  As it is, you are almost guaranteed to have to iterate through every result set you get at least three times:  Once to add the items to your list, once again internally when the list is converted to an array, and finally when the calling code actually uses the array.  Returning the raw datareader means you only have to iterate through the results once.
public IDataReader MySQLQuery(string qry)
{
    if (OdbcCon.State == ConnectionState.Open)
    {
        OdbcCom = new System.Data.Odbc.OdbcCommand(qry, OdbcCon);
        OdbcDR = OdbcCom.ExecuteReader();
    }
    return OdbcDR;
}

Open in new window

0
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 
LVL 1

Author Comment

by:SaltyDawg
ID: 21867642
I'm trying to return the results using the function presented.

///////////////////////////////////////////////////////////////
            clsMySqlODBCConnection MySQLConn = new clsMySqlODBCConnection();
            IDataReader qryResults = null;

            qryResults = MySQLConn.MySQLQuery("SELECT * FROM `MainIndex` WHERE `SerialNumber` =110477");

            qryResults["ItemIndexNumber"];
///////////////////////////////////////////////////////////////
Am I getting so far. Or what do I have wrong?
0
 
LVL 18

Expert Comment

by:jcoehoorn
ID: 21867659
You have to read from your datareader before referencing any columns.
0
 
LVL 1

Author Comment

by:SaltyDawg
ID: 21867859
I'm sorry I'm still not getting this right. By the way I was studying this and found SqlDataReader, whats the difference? Some say SqlDataReader runs faster...
0
 
LVL 1

Author Comment

by:SaltyDawg
ID: 21867933
Am I anywhere close here:

            clsMySqlODBCConnection MySQLConn = new clsMySqlODBCConnection();

            MySQLConn.MySQLQuery("SELECT * FROM `MainIndex` WHERE `SerialNumber` =110477");

            MySQLConn.OdbcDR[0];

I'm sure MySQLConn.OdbcDR[0]; is wrong, just don't know where to go from there
0
 
LVL 1

Author Comment

by:SaltyDawg
ID: 21868057
Oh Think I have it now, this seems to work:

            string tStr1,tStr2 = null;
            string tResults = null;

            MySQLConn.MySQLQuery("SELECT * FROM `MainIndex` WHERE `SerialNumber` =110477");

            while (MySQLConn.OdbcDR.Read())
            {
                tStr1 = Convert.ToString(MySQLConn.OdbcDR["ItemIndexNumber"]);
                tStr2 = Convert.ToString(MySQLConn.OdbcDR["SerialNumber"]);
                MessageBox.Show(tStr1 + " - " + tStr2);
            }

0
 
LVL 18

Expert Comment

by:jcoehoorn
ID: 21868312
Odbc is generally slower than a native provider.  However, SqlDataReader is for SQL Server only.  For MySQL I would install the MySQL provider, Connector/Net:
http://www.mysql.com/products/connector/net/

0
 
LVL 1

Author Closing Comment

by:SaltyDawg
ID: 31470611
Thanks alot
0

Featured Post

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

As a database administrator, you may need to audit your table(s) to determine whether the data types are optimal for your real-world data needs.  This Article is intended to be a resource for such a task. Preface The other day, I was involved …
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

778 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question