Compartilhar via


Como: Inserir novos registros em um banco de dados

To insert new records into a database, you can use the TableAdapter.Update method, or one of the TableAdapter's DBDirect methods (specifically the TableAdapter.Insert method).Para obter mais informações, consulte Visão geral do TableAdapter.

If your application does not use TableAdapters, you can use command objects to interact and insert new records in your database (for example, SqlCommand).

Use the TableAdapter.Update method when your application uses datasets to store data.The Update method sends all changes (updates, inserts, and deletes) to the database.

Use the TableAdapter.Insert method when your application uses objects to store data, or when you want finer control over creating new records in the database.

If your TableAdapter does not have an Insert method, it means that either the TableAdapter is configured to use stored procedures or its GenerateDBDirectMethods property is set to false.Try setting the TableAdapter's GenerateDBDirectMethods property to true from within the Dataset Designer and then save the dataset to regenerate the TableAdapter.If the TableAdapter still does not have an Insert method, then the table probably does not provide enough schema information to distinguish between individual rows (for example, no primary key is set on the table).

Inserir novos registros usando o TableAdapters

Os TableAdapters fornecem maneiras diferentes para inserir novos registros em um banco de dados, dependendo dos requisitos do seu aplicativo.

If your application uses datasets to store data, then you can simply add new records to the desired DataTable in the dataset, and then call the TableAdapter.Update method.The TableAdapter.Update method takes any changes in the DataTable and sends those changes to the database (including modified and deleted records).

Para inserir novos registros em um banco de dados usando o método TableAdapter.Update

  1. Add new records to the desired DataTable by creating a new DataRow and adding it to the Rows collection.Para obter mais informações, consulte Como: Adicionar linhas a uma DataTable.

  2. After the new rows are added to the DataTable, call the TableAdapter.Update method.You can control the amount of data to update by passing in either an entire DataSet, a DataTable, an array of DataRows, or a single DataRow.

    The following code shows how to add a new record to a DataTable and then call the TableAdapter.Update method to save the new row to the database.(This example uses the Northwind database Region table.)

    ' Create a new row.
    Dim newRegionRow As NorthwindDataSet.RegionRow
    newRegionRow = Me.NorthwindDataSet._Region.NewRegionRow()
    newRegionRow.RegionID = 5
    newRegionRow.RegionDescription = "NorthWestern"
    
    ' Add the row to the Region table
    Me.NorthwindDataSet._Region.Rows.Add(newRegionRow)
    
    ' Save the new row to the database
    Me.RegionTableAdapter.Update(Me.NorthwindDataSet._Region)
    
    // Create a new row.
    NorthwindDataSet.RegionRow newRegionRow;
    newRegionRow = northwindDataSet.Region.NewRegionRow();
    newRegionRow.RegionID = 5;
    newRegionRow.RegionDescription = "NorthWestern";
    
    // Add the row to the Region table
    this.northwindDataSet.Region.Rows.Add(newRegionRow);
    
    // Save the new row to the database
    this.regionTableAdapter.Update(this.northwindDataSet.Region);
    

If your application uses objects to store the data in your application, you can use the TableAdapter.Insert method to create new rows directly in the database.The Insert method accepts the individual values for each column as parameters.A invocação do método insere um novo registro no banco de dados com os valores de parâmetro repassados.

O procedimento a seguir usa a tabela Region do banco de dados Northwind como um exemplo.

Para inserir novos registros em um banco de dados usando o método TableAdapter.Insert

  • Chame o método Insert do TableAdapter, passando os valores para cada coluna como parâmetros.

    Observação:

    Se você não tiver uma instância disponível, crie a instância no TableAdapter que você deseja usar.

    Dim regionTableAdapter As New NorthwindDataSetTableAdapters.RegionTableAdapter
    
    regionTableAdapter.Insert(5, "NorthWestern")
    
    NorthwindDataSetTableAdapters.RegionTableAdapter regionTableAdapter = 
        new NorthwindDataSetTableAdapters.RegionTableAdapter();
    
    regionTableAdapter.Insert(5, "NorthWestern");
    

Inserir novos registros usando objetos Command

O exemplo a seguir insere novos registros diretamente para um banco de dados usando objetos Command.For more information on using command objects to execute commands and stored procedures, see Buscando dados em seu aplicativo.

O procedimento a seguir usa a tabela Region do banco de dados Northwind como um exemplo.

Para inserir novos registros em um banco de dados usando objetos Command

  • Create a new command object, set its Connection, CommandType, and CommandText properties.

    Dim sqlConnection1 As New System.Data.SqlClient.SqlConnection("YOUR CONNECTION STRING")
    
    Dim cmd As New System.Data.SqlClient.SqlCommand
    cmd.CommandType = System.Data.CommandType.Text
    cmd.CommandText = "INSERT Region (RegionID, RegionDescription) VALUES (5, 'NorthWestern')"
    cmd.Connection = sqlConnection1
    
    sqlConnection1.Open()
    cmd.ExecuteNonQuery()
    sqlConnection1.Close()
    
    System.Data.SqlClient.SqlConnection sqlConnection1 = 
        new System.Data.SqlClient.SqlConnection("YOUR CONNECTION STRING");
    
    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.CommandText = "INSERT Region (RegionID, RegionDescription) VALUES (5, 'NorthWestern')";
    cmd.Connection = sqlConnection1;
    
    sqlConnection1.Open();
    cmd.ExecuteNonQuery();
    sqlConnection1.Close();
    

Segurança

Você deve ter acesso ao banco de dados que você está tentando se conectar, bem como permissão para executar inserções na tabela desejada.

Consulte também

Tarefas

Como: Excluir registros em um banco de dados

Como: Atualizar registros em um banco de dados

Como: Salvar dados de um objeto a um banco de dados

Outros recursos

Guia de Introdução para acesso a dados

Conectando-se a Dados no Visual Studio

Preparando seu aplicativo para receber dados

Buscando dados em seu aplicativo

Exibindo dados em formulários em aplicativos do Windows

Editar dados no seu aplicativo

Validando Dados

Salvando dados