71319

Calling stored procedure values into the console application C#

Question:

I have a stored procedure that its been called by a console application in C#. The stored procedure has some required parameters to be executed. What I am trying to achieve its to be able to enter one of the required parameters into the console once the console is executed.

Something like having a text into the console asking to enter the project name and then hit on enter.

Here's my code:

try { using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Test"].ConnectionString)) { string outCsvFile = @"D:\\test\\test.csv"; SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Connection = conn; sqlCmd.CommandText = "projects"; //Adding values to the stored procedure sqlCmd.Parameters.AddWithValue("@ProjectTitle", "Test Project 1"); //this value I would like to add it when the console application is executed when I will hit on enter. sqlCmd.Parameters.AddWithValue("@Category", ""); conn.Open(); SqlDataReader reader = sqlCmd.ExecuteReader(); using (System.IO.StreamWriter file = new System.IO.StreamWriter(outCsvFile)) { file.WriteLine(reader.GetName(0) + ',' + reader.GetName(1)); while (reader.Read()) file.WriteLine(reader[0].ToString() + ',' + reader[1].ToString()); } conn.Close(); } } catch (Exception e) { Console.WriteLine(e.Message); System.Threading.Thread.Sleep(8000); }

Answer1:

If I understand your question below is the code for you.

//Adding values to the stored procedure Console.WriteLine("Please enter project title and press Enter"); string projectTitle = Console.ReadLine(); while (String.IsNullOrWhiteSpace(projectTitle)) { Console.WriteLine("Please enter project title and press Enter"); projectTitle = Console.ReadLine(); } string outCsvFile = string.Format(@"D:\\test\\{0}.csv", projectTitle); if (System.IO.File.Exists(outCsvFile)) { throw new ApplicationException("File already exist Name " + outCsvFile); } sqlCmd.Parameters.AddWithValue("@ProjectTitle", projectTitle); //this value I would like to add it when the console application is executed when I will hit on enter.

Answer2:

There are two ways that I know a console application can get input. One is from the ReadLine or ReadKey method. The other is from the command line argument. If you run your executable in command prompt and supply some values, you can get it in your console app.

using System; namespace ConsoleParameter { class Program { static void Main(string[] args) { // get from the command line parameter Console.WriteLine("Parameter in command line"); foreach (var arg in args) { Console.WriteLine(arg); } // get from keyboard input when the console is running Console.WriteLine("Please input something"); var value = Console.ReadLine(); Console.WriteLine("You entered {0}", value); Console.ReadKey(true); } } }

Screenshot of running the console in command prompt. <a href="https://i.stack.imgur.com/wOXy0.png" rel="nofollow"><img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/wOXy0.png" data-original="https://i.stack.imgur.com/wOXy0.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

You can also provide the command line arguments in Visual Studio, so you can test it without running it from the command prompt.<a href="https://i.stack.imgur.com/jdQgY.png" rel="nofollow"><img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/jdQgY.png" data-original="https://i.stack.imgur.com/jdQgY.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

Answer3:

The values will be in order.

var someEnteredValue = Console.ReadLine();

//Hit enter and then:

var nextEnteredValue = Console.ReadLine();

Recommend

  • Excel Jet OLE DB: Inserting a DateTime value
  • Is it possible to pass a parameter that is DB.null and set a value in the database equal to that?
  • Solving the problem of SQLinjection
  • How to resolve “ Multiplicity is not valid in Role” error?
  • Argument 5: cannot convert from 'System.Drawing.Image' to 'string' - calling cla
  • Scrolling News Ticker Jquery - Issues
  • Using extern @class in order to add a category?
  • “A GKScore must specify a leaderboard.”
  • Get used tables from sql query [duplicate]
  • Django Haystack Rebuild Index
  • Does Apportable support to build library binary (.a/.so)?
  • What does “t” refer to in this SQL?
  • what makes a request a new request in asp.net C#
  • Check for zero lines output from command over SSH
  • nonblocking BIO_do_connect blocked when there is no internet connected
  • Jenkins: FATAL: Could not initialize class hudson.util.ProcessTree$UnixReflection
  • Keep this build forever option - Jenkins
  • Converting a WriteableBitmap image ToArray in UWP
  • Bad request using file_get_contents for PUT request in PHP
  • MailKit: The IMAP server replied to the 'EXAMINE' command with a 'BAD' response
  • Yii2: Config params vs. const/define
  • Switching to Release Build causes runtime error in Web Reference
  • Is there any way to access browser form field suggestions from JavaScript?
  • NetLogo BehaviorSpace - Measure runs using reporters
  • Spring security and special characters
  • How to redirect a user to a different server and include HTTP basic authentication credentials?
  • Can I make an Android app that runs a web view in Chrome 39?
  • JSON with duplicate key names losing information when parsed
  • Hazelcast - OperationTimeoutException
  • Display Images one by one with next and previous functionality
  • QuartzCore.framework for Mono Develop
  • KeystoneJS: Relationships in Admin UI not updating
  • C# - Getting references of reference
  • JTable with a ScrollPane misbehaving
  • Angular 2 constructor injection vs direct access
  • Java static initializers and reflection
  • Android Google Maps API OnLocationChanged only called once
  • LevelDB C iterator
  • Linking SubReports Without LinkChild/LinkMaster
  • UserPrincipal.Current returns apppool on IIS