Chapter 21: Database Connection in C

Connect to SQLite, PostgreSQL, MySQL, Supabase. In this chapter, you will learn database connection in depth with C code examples, explanations, and best practices.

Overview

This chapter covers database connection for Kungfu.js developers using C. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.

Why This Matters

Understanding database connection is essential because it is a core part of building web applications. Every real-world app needs to handle connect to sqlite, postgresql, mysql, supabase. Skipping this chapter would leave a gap in your knowledge that would cause problems later.

Code Example

Here is how to work with databases in C:

// SQLite (local development)
let db = Db::connect(&DbConfig {
    url: "sqlite::memory:".into(),
    max_connections: 5,
    min_connections: 1,
}).await?;

// PostgreSQL (Supabase, Neon, Railway)
let db = Db::connect(&DbConfig {
    url: "postgres://user:pass@host:5432/db".into(),
    max_connections: 10,
    min_connections: 2,
}).await?;

// MySQL
let db = Db::connect(&DbConfig {
    url: "mysql://user:pass@host:3306/db".into(),
    max_connections: 10,
    min_connections: 2,
}).await?;

How the ORM Works

The Kungfu.js ORM uses parameterized queries. This means user input never gets interpolated into SQL strings. Instead, placeholders like $1, $2 are used, and the actual values are passed separately. This makes SQL injection impossible.

For example, if you search for a user by email, the ORM generates: SELECT * FROM users WHERE email = $1 and passes the email value as a parameter. Even if the email contains SQL code like ' OR 1=1 --, it is treated as a plain string, not as SQL.

Common Mistakes

  • Not reading the documentation: Always check the API reference when something does not work as expected.
  • Skipping security: Never disable the default middleware unless you have a very good reason. Security is not optional.
  • Not testing: Write tests for your handlers. Kungfu.js makes this easy with the built-in test utilities.

Summary

In this chapter, you learned about database connection in C. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.

What is Next?

In chapter 22, we will cover Defining Models: Create database models with attributes.