pub fn insert<T: SqlQuery + SqlParams>(
conn: &Connection,
entity: T,
) -> Result<usize, Error>
Expand description
§insert
Inserts a new record into the SQLite database.
§Parameters
conn
: SQLite database connectionentity
: Data object to be inserted (must implement SqlQuery and SqlParams traits)
§Return Value
Result<usize, rusqlite::Error>
: On success, returns the number of inserted records; on failure, returns Error
§Struct Definition
Structs used with this function should be annotated with the following derive macros:
#[derive(Insertable, SqlParams)] // Required macros
#[table("table_name")] // Table name to insert into
pub struct MyEntity {
pub field1: String,
pub field2: i32,
// ...
}
Insertable
: Automatically generates SQL INSERT statementsSqlParams
: Automatically generates SQL parameters#[table("table_name")]
: Specifies the table name for the insertion
§Example Usage
use rusqlite::{Connection, Result};
use parsql_macros::{Insertable, SqlParams};
use parsql_sqlite::insert;
fn main() -> Result<()> {
// Create a database connection
let conn = Connection::open("test.db")?;
// Create the table
conn.execute("CREATE TABLE users (name TEXT, email TEXT, state INTEGER)", [])?;
// Define your entity with appropriate macros
#[derive(Insertable, SqlParams)]
#[table("users")]
pub struct InsertUser {
pub name: String,
pub email: String,
pub state: i16,
}
// Create a new instance of your entity
let insert_user = InsertUser {
name: "John".to_string(),
email: "john@example.com".to_string(),
state: 1,
};
// Insert into database
let insert_result = insert(&conn, insert_user)?;
println!("Insert result: {:?}", insert_result);
Ok(())
}