K
K
kykyryky2016-01-30 14:18:45
Programming
kykyryky, 2016-01-30 14:18:45

How to call a stored procedure from an application?

The project code has a method that receives an sql query as input, and displays the contents of the table in the DataGridView as output:

private void GetData(string selectCommand)
        {
            String connectionString = @"Data Source=WIN-940; Initial Catalog = auto_repair;User ID=test;Password=123";
                        
            dataAdapter = new SqlDataAdapter(selectCommand, connectionString);
            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
            DataTable table = new DataTable();
            table.Locale = System.Globalization.CultureInfo.InvariantCulture;
            dataAdapter.Fill(table);
            bindingSource1.DataSource = table;
            dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
        }

I call like this:
private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = bindingSource1;
            GetData("select * from Vehicles");
        }

I have formatted large queries as stored procedures, but I can't call them using what I have done. Just passing the name of the procedure to GetData doesn't work.
I found something like this on the Internet, and I was completely confused.
using (var sqlConn = new SqlConnection("строка соединения"))
{ 
  var sqlCmd = new SqlCommand("Имя Stored Procedure", sqlConn);
  sqlCmd.CommandType = CommandType.StoredProcedure;
  
  sqlConn.Open();
  sqlCmd.ExecuteNonQuery();
}

This, as I understand it, is a completely different way of executing queries in the database, and I don’t understand how to convert it into something similar to mine with output to the dataGrid, I need help or explanation. Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Nemiro, 2016-01-30
@kykyryky

dataAdapter = new SqlDataAdapter("Имя процедуры", connectionString);
dataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;

Either using SqlCommand :
var connection = new SqlConnection(connectionString);
// connection.Open();
var cmd = new SqlCommand("Имя процедуры", connection);
cmd.CommandType = CommandType.StoredProcedure;
dataAdapter = new SqlDataAdapter(cmd);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question