Certainly! Here’s an example of Swift code that demonstrates how to add data to a SQLite database using the SQLite.swift library:
import SQLite
// Create a connection to the SQLite database
let db = try Connection("path_to_your_database")
// Create a table object
let yourTable = Table("your_table")
// Define the columns in the table
let column1 = Expression<String>("column1")
let column2 = Expression<String>("column2")
do {
// Insert data into the table
let insert = yourTable.insert(column1 <- "DataValue1", column2 <- "DataValue2")
// Execute the insert statement
try db.run(insert)
print("Data inserted successfully.")
} catch {
print("Error inserting data: \(error)")
}
Make sure to replace the following placeholders with your own values:
path_to_your_database
: The file path or URL to your SQLite database file.your_table
: The name of the table where you want to add data.column1, column2
: The names of the columns in the table where you want to add data."DataValue1", "DataValue2"
: The values you want to add tocolumn1
andcolumn2
respectively.
This code uses the SQLite.swift library to establish a connection to the SQLite database, define the table and columns, create an insert statement, execute the statement, and handle any potential errors that may occur. The code also outputs a success message if the data insertion is successful.
Make sure to include the SQLite.swift library in your Swift project. You can add it using Swift Package Manager or Cocoapods, depending on your project’s setup.