Query string in c # SQL command

First of all .. excuse me for my poor English, I hope they understand you.

I regularly work with LINQ, new SQL for me.

I am trying to do the following: I have the following method in C #:

public string niceMethod() { SqlConnection connection = new SqlConnection("Data Source=*******;Integrated Security=False;"); string commandtext = "SELECT bla FROM items WHERE main = 1"; SqlCommand command = new SqlCommand(commandtext, connection); connection.Open(); string tDate = (string)command.ExecuteScalar(); connection.Close(); return tDate; } 

I have a page, for example: items.aspx?nID=144

how can i do that the SELECT command will be with querystring and this will take the value

from the "items" table by identifier (nID) displayed at?

The table has a design, for example: id, title, bla, main.

+6
source share
2 answers

Try something like this:

 int nID = int.Parse(Request.QueryString["nID"].ToString()); niceMethod(nID); public string niceMethod(int nID) { using (var conn = new SqlConnection("Data Source=server;Initial Catalog=blah;Integrated Security=False;")) using (var cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = @"SELECT bla, id, title FROM items WHERE main = @nID"; cmd.Parameters.AddWithValue("@nID", nID); string tDate = cmd.ExecuteScalar().ToString(); return tDate; } } 
+6
source

Try the following:

Pay attention to (Request.QueryString["nID"] ?? "0").ToString() , this is really important, so you will not get an exception if there is no query.

  public string niceMethod() { string tDate = ""; string ID = (Request.QueryString["nID"] ?? "0").ToString(); // Get the nID query, incase there is no query, returns 0. using (SqlConnection connection = new SqlConnection("Data Source=*******;Integrated Security=False;")) { string commandtext = "SELECT bla FROM items WHERE id=@ID "; //@ID Is a parameter SqlCommand command = new SqlCommand(commandtext, connection); command.Parameters.AddWithValue("@ID", ID); //Adds the ID we got before to the SQL command connection.Open(); tDate = (string)command.ExecuteScalar(); } //Connection will automaticly get Closed becuase of "using"; return tDate; } 
+5
source

Source: https://habr.com/ru/post/891923/


All Articles