简体   繁体   中英

Why does my SQL Server database do not save the data using a procedure - C#

I'm trying to make a procedure and call it when I need to insert some data.

When I execute the application and click "save", the application does not respond for at least 15 seconds before returning to normal. But the data isn't saved.

I made a test procedure and some test functions to test it.

The connection string:

public static string Cn = 
       "Data Source = THIAGO\\SERVIDORSQL; Initial Catalog = DBClinica; Integrated Security = true";

The data layer code to insert test data:

public string Adicionar_Teste(Dados_Pacientes dados_Pacientes)
{
    string resp = "";

    SqlConnection sqlConnection = new SqlConnection();

    try
    {
        sqlConnection.ConnectionString = Conexao.Cn;//cn is the SQL DATABASE path
        sqlConnection.Open();

        // SQL command
        SqlCommand sqlCmd = new SqlCommand();
        sqlCmd.Connection = sqlConnection;
        sqlCmd.CommandText = "ProcAdicionar_Teste";
        sqlCmd.CommandType = CommandType.StoredProcedure;

        SqlParameter parTeste = new SqlParameter();
        parTeste.ParameterName = "@Teste";
        parTeste.SqlDbType = SqlDbType.VarChar;
        parTeste.Size = 10;
        parTeste.Value = dados_Pacientes.Nome;
        sqlCmd.Parameters.Add(parTeste);
    }
    catch (Exception ex)
    {
        return resp = ex.Message;
    }
    finally
    {
        if (sqlConnection.State == ConnectionState.Open) 
            sqlConnection.Close();
    }

    return resp;
}

The business layer:

public static string AdicionarTeste(string teste)
{
    Dados_Pacientes dados = new Dados_Pacientes();
    dados.Nome = teste;

    return dados.Adicionar_Teste(dados);
}

The form method called when the user clicks in 'save':

private void AdicionarTeste()
{
    string x = TextBoxNomeDoPaciente.Text;
    Negocios_Pacientes.AdicionarTeste(x);
}

SQL Server name and path:

and

SQL Server database structure

Stored procedure:

ALTER PROCEDURE [dbo].[procAdicionar_Teste]
    @Teste VARCHAR(10)
AS
    INSERT INTO Teste (Teste) 
    VALUES (@Teste)

You are not executing the command. You need to add below statement at the end of the try block.

sqlCmd.ExecuteNonQuery();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM