Как вставить значения в SQLite по нажатию кнопки (WPF) - PullRequest
0 голосов
/ 11 ноября 2018

Я пытаюсь вставить значения в базу данных SQLite с помощью следующего кода:

private void btnAdd_Click(object sender, RoutedEventArgs e)
{
     string database_connection = "Data Source=database.db;Version=3;";
     SQLiteConnection connection = new SQLiteConnection(database_connection);
     connection.Open();

     string query = String.Format("INSERT INTO `database`.`airports`(`id`, `airportName`, `airportCity`, `active`) VALUES ('"+txtAirportId+"','"+txtAirportName+"','"+txtAirportCity+"','"+1+"')");
     SQLiteCommand command = new SQLiteCommand(query, connection);
     SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(command);
     connection.Close();

     txtAirportId.Clear();
     txtAirportName.Clear();
     txtAirportCity.Clear();

}

И это код xaml:

<DataGrid x:Name="dgAirports" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="100" Width="272" ItemsSource="{Binding}" AutoGenerateColumns="False" CanUserAddRows="false" VerticalScrollBarVisibility="Hidden">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Шифра" Binding="{Binding Path = id}" Width="*"/>
                <DataGridTextColumn Header="Назив" Binding="{Binding Path = airportName}"  Width="*"/>
                <DataGridTextColumn Header="Град" Binding="{Binding Path = airportCity}" Width="*"/>
            </DataGrid.Columns>
        </DataGrid>

        <Label x:Name="lblAirportId" Content="ИД" HorizontalAlignment="Left" Margin="123,115,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="txtAirportId" Text="{Binding ElementName=dgAirports, Path=SelectedValue.id}" HorizontalAlignment="Left" Height="23" Margin="157,115,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="125"/>

        <Label x:Name="lblAirportName" Content="Назив" HorizontalAlignment="Left" Margin="109,142,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="txtAirportName" Text="{Binding ElementName=dgAirports, Path=SelectedValue.airportName}" HorizontalAlignment="Left" Height="23" Margin="157,143,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="125"/>

        <Label x:Name="lblAirportCity" Content="Град" HorizontalAlignment="Left" Margin="115,168,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="txtAirportCity" Text="{Binding ElementName=dgAirports, Path=SelectedValue.airportCity}" HorizontalAlignment="Left" Height="23" Margin="157,171,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="125"/>


        <Button x:Name="btnShow" Content="Прикажи" HorizontalAlignment="Left" Margin="10,115,0,0" VerticalAlignment="Top" Width="75" Click="btnShow_Click"/>
        <Button x:Name="btnAdd" Content="Додај" HorizontalAlignment="Left" Margin="10,142,0,0" VerticalAlignment="Top" Width="75" Click="btnAdd_Click"/>
    </Grid>

Поэтому, когда я нажимаю btnAddничего не происходит, но я не получаю никаких ошибок.Итак, что мне не хватает и как вставить эти значения в таблицу «аэропортов»?

1 Ответ

0 голосов
/ 11 ноября 2018

Просто измените свою функцию следующим образом:

private void btnAdd_Click(object sender, RoutedEventArgs e)
{
    string database_connection = "Data Source=database.db;Version=3;";
    SQLiteConnection connection = new SQLiteConnection(database_connection);
    connection.Open();

    string query = String.Format($"INSERT INTO `database`.`airports`(`id`, `airportName`, `airportCity`, `active`) VALUES ('{txtAirportId }','{txtAirportName }','{txtAirportCity}','1')");
    SQLiteCommand command = new SQLiteCommand(query, connection);
    command.ExecuteNonQuery();

    txtAirportId.Clear();
    txtAirportName.Clear();
    txtAirportCity.Clear();
}

Кстати: ваш код все равно будет не хорошим. По крайней мере, у вас будет уязвимость SQL Injection, если вы просто обратитесь к строке. Используйте параметры или прочитайте о Entity Framework Core Технология.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...