0

I am very new to database queries and even more so, Oracle. I am also new to development work and, believe it or not, am creating this an for work purely out of frustration with the current process. Anyway, I am attempting to collect input from a multi-line text box and run a query. Each line corresponds to a single string that needs to be passed into the WHERE statement and the results will be dumped into a data table. Unfortunately, Oracle has still not released its developer tools for VS2019 so I am having to do this the harder way.

UPDATE # 2: I have completely rebuilt the query since it was not running even when using known working code from another query. Below is what I have pieced together from various places on the interwebs. While debugging, it appears to parse and format the text correctly and pass it into the OracleParameter without issue. I am getting a Missing Expression error but I don't know what I am missing.

var connString = 
ConfigurationManager.ConnectionStrings["dB"].ConnectionString;
string query = "SELECT col1, col2, col3, col4 FROM table WHERE col5 IN (";

using (OracleConnection conn = new OracleConnection(connString))
         try
         {
            var input = "";
            input = uniLookup.UniList;
            var uniList = string.Join(",", Regex.Split(input, @"(?:\r\n|\n|\r)"));

            string allParams = uniList;
            string formattedParams = allParams.Replace(" ", string.Empty);
            string[] splitParams = formattedParams.Split(',');

            List<OracleParameter> parameters = new List<OracleParameter>();

            using (OracleCommand cmd = new OracleCommand(query, conn))
            {
                for (int i = 0; i < splitParams.Length; i++)
                {
                    query += @":Uni" + i + ",";
                    parameters.Add(new OracleParameter(":Uni" + i, splitParams[i]));
                    {
                        query = query.Substring(0, (query.Length - 1));
                        query += ')';
                        conn.Open();
                        using (OracleDataReader reader = cmd.ExecuteReader())  <==ERROR
                        {
                            if (!reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    reader.Read();
                                    {
                                        MessageBox.Show(reader.GetString(1));
                                    }
                                }
                            }
gearhead28
  • 11
  • 3
  • "*Is there a way to create an array from my textbox data and pass the entire array into a single search query*" The answer is yes – TheGeneral Nov 23 '19 at 04:02
  • You would want parameterised queries to start with, also it would help if we knew what was in the where clause more specifically – TheGeneral Nov 23 '19 at 04:04
  • I am using the WHERE clause as the key to match each line in the text box to its corresponding row of data in the database. Each line of text is a string of numbers, letters, and characters but is all one "word". I am only match a single value in the WHERE clause so the full extend of the syntax is just "WHERE altColumn = 'line from textbox'" – gearhead28 Nov 23 '19 at 04:09
  • just build up the query with `and`s or even better `in` – TheGeneral Nov 23 '19 at 04:10
  • I will have to go back researching. I've tried using "IN" but I can't ever seem to get the syntax correct. I have been banging my head against the wall for almost a week now and the method above is the only one that I was able to get "working". – gearhead28 Nov 23 '19 at 04:12
  • you can use `IN` in this way as, `string query = "SELECT dummyCol FROM dummytable WHERE IN altCol = " + text+";` where you just have to change your `text` as `text="'value1','value2','value3'";` this will not produce any syntax error – Muhammad Abdullah Khan Nov 23 '19 at 06:49

1 Answers1

0

You can use IN in your where clause in this way to get rows from multiple values as: string query = "SELECT dummyCol FROM dummytable WHERE altCol IN ("+text+");";

where you just have to change your text as text="'value1','value2','value3'"; this will not produce any syntax error. You can convert your multi line text into same comma separated values using this :

            foreach (String s in textBox1.Text.Split('\n'))
            {
                text +="'"+ s+"',";
            }
            text = text.TrimEnd(',');

this will help you achieve what you need. you can ask If there is any confusion.

Your final code will become :

public void GetData()
        {
            if (string.IsNullOrWhiteSpace(textbox1.Text) || textbox1.Text == "")
            {
                MessageBox.Show("Please Enter at least 1 Value and Try Again!");
            }
            else
            {
                System.Data.DataTable dt = new System.Data.DataTable();
                // string[] lines = textbox1.Text.Split('\n');


                string text = "";
                foreach (String s in textBox1.Text.Split('\n'))
                {
                    text += "'" + s + "',";
                }
                text = text.TrimEnd(',');

                //Connection Credentials
                string credentials = "Credentials";
                string query = "SELECT dummyCol FROM dummytable WHERE altCol IN ("+text+");";

                OracleConnection conn = new OracleConnection(credentials);

                try
                {
                    //Open The Connection
                    conn.Open();
                    using (OracleCommand cmd = new OracleCommand(query, conn))
                    {
                        //Call the Oracle Reader
                        using (OracleDataReader reader = cmd.ExecuteReader())
                        {
                            if (!reader.HasRows)
                            {
                                MessageBox.Show("Unable to Retrieve Data");
                                return;
                            }
                            else if (reader.HasRows)
                            {
                                reader.Read();
                                DataRow row = dt.NewRow();
                                // create variables to accept reader data for each column
                                // insert data from query into each column here
                                dt.Rows.Add(row);
                            }
                        }
                    }
                }
         }

        }

  • I am going to give this a try since I haven't been able to get the parameterized method workng. I will report back later today. Thank you for this example! – gearhead28 Nov 23 '19 at 12:06
  • I tried implementing this example but was unsuccessful. I don't think the string that was being passed into the query was formatted correctly. I need to spend some more time looking at this later this evening. – gearhead28 Nov 23 '19 at 22:24
  • you can try debugging by enabling the Break Point in Visualstudio, so that you can get the query string and directly check in your database server by execution. This will help you in getting error more precisely. – Muhammad Abdullah Khan Nov 24 '19 at 05:14
  • @gearhead28, I have updated my answer, Query is now perfect. I tested in my system. – Muhammad Abdullah Khan Nov 24 '19 at 05:24
  • I tried your updated answer but I am still not able to return any results. When I debug i get this error "InstanceBranch 'conn.InstanceBranch' threw an exception of type 'System.NullReferenceException' string {System.NullReferenceException}. I have confirmed that "text" does contain text so I am not sure what is going on. – gearhead28 Nov 24 '19 at 11:47
  • Why not you try breakpoint on text so that you can verify what is in text, then use breakpoint on query in next step. – Muhammad Abdullah Khan Nov 24 '19 at 12:09
  • 1
    Sorry for my delayed response. I had to take a break. I was getting very frustrated . I have confirmed that the value of "text" is being populated and passed into the query but I am getting a null result from my data reader. I have copied know working code for a single item search into my viewmodel and tried running that and it is still failing. At this point I think this is related to some weird bug that I can't seem to trace down. I have decided to delete this viewmodel and start over. I'll report back in a few days. Thanks for all your help, we are definitely on the right path! – gearhead28 Nov 25 '19 at 11:10
  • I have updated my code above. I have used your code and added a few additional pieces to make sure I cover all my bases. Now i am just getting a missing expression error but i think we are very close! – gearhead28 Nov 28 '19 at 09:22
  • can you please show the error , so that I may assist you with this. – Muhammad Abdullah Khan Nov 28 '19 at 09:36
  • ERROR: Oracle.ManagedDataAccess.Client.OracleException (0x80004005): ORA-00936: missing expression. – gearhead28 Nov 28 '19 at 09:56
  • Try to remove semicolon at the end of your query, this is sometimes an issue for Oracle. – Muhammad Abdullah Khan Nov 28 '19 at 09:59
  • If I remove the semicolon it doesn't build because the line is not terminated. – gearhead28 Nov 28 '19 at 10:06
  • use this `string query = "SELECT dummyCol FROM dummytable WHERE altCol IN ("+text+")";` , i just removed semicolon inthe string, not from the end of line, – Muhammad Abdullah Khan Nov 28 '19 at 10:13
  • I believe that is how I currently have my string query set up. This is the ending of the line... query += ")"; – gearhead28 Nov 28 '19 at 10:25