Sudharsun Sudharsun - 2 months ago 15
MySQL Question

How to specify inputs in runtime

How do i specify SQL query input in run time.

Ex;

insert into table1 value('b','a');


to be typed typed in run time

a= inn
b= out

Answer
    cn = new SqlConnection("YourConnectionString");

    string sql = "INSERT INTO table1(columnName1, ColumnName2) VALUES (@columnName1, @ColumnName2)";

    cn.Open();
    SqlCommand cmd = new SqlCommand(sql, cn);

    cmd.Parameters.AddWithValue("@columnName1", textbox.text);
    cmd.Parameters.AddWithValue("@columnName2", textbox2.text);

    cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();
    cn.Close();

Hope this helps.....

EDIT - For stored proc you can do this:

    USE [DatabaseName]
    GO
    /****** Object:  StoredProcedure [dbo].[DatabaseName]  ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE PROCEDURE [dbo].[storedProcName]

    @param1 varchar(50)
   ,@param2 varchar(50)

    AS

    BEGIN

    INSERT INTO [dbo].[tableName]
          ([ComunName1]
          ,[ComunName2]
    VALUES
          (
           @param1 
          ,@param2
          )

    END

And in your code you can call the stored proc as follows:

    c#:
    cn = new SqlConnection("YourConnectionString");
    sql = "yourStoredProcName"; 
    command = new SqlCommand(sql, cn); 
    command.CommandType = CommandType.StoredProcedure; 
    command.Parameter.Add(new SqlParameter("@param1", SqlDbType.VarChar)).Value = textbox1.text; 
    command.Parameter.Add(new SqlParameter("@param2", SqlDbType.VarChar)).Value = textbox2.text; 
    connection.Open();  
    command.ExecuteNonQuery(); 
    connection.Close();

Hope this helps with the stored proc.....

Comments