Lokang 

Swift and MySQL

MySQL

Creating a CRUD application in Swift with a MySQL database involves using Swift for the server-side and a MySQL driver to connect to the database. Below are the steps to create such an application.

Setup

Install MySQL and MySQL Swift Connector:

Make sure MySQL is installed on your system. For Swift, we can use the mysql-swift library.

Install the library using Swift Package Manager by adding it to your Package.swift:

// swift-tools-version:5.3
import PackageDescription
let package = Package(
   name: "CRUDApp",
   dependencies: [
       .package(url: "https://github.com/novi/mysql-swift.git", from: "0.9.1")
   ],
   targets: [
       .target(
           name: "CRUDApp",
           dependencies: ["MySQL"]
       )
   ]
)

Create MySQL Database and Table:

Open your MySQL client and create a database and a table:

CREATE DATABASE crud_db;
USE crud_db;
CREATE TABLE users (
 id INT AUTO_INCREMENT PRIMARY KEY,
 name VARCHAR(255),
 email VARCHAR(255)
);

Code

Create a Swift File:

Create a new Swift file, for example, main.swift.

Import Libraries and Connect to MySQL:

import MySQL
let mysql = try MySQL.Database(
   host: "localhost",
   user: "root",
   password: "password",
   database: "crud_db"
)

Define CRUD Operations:

struct User {
   var id: Int?
   var name: String
   var email: String
}
func createUser(name: String, email: String) throws {
   let query = "INSERT INTO users (name, email) VALUES (?, ?)"
   try mysql.execute(query, [name, email])
   print("User added.")
}
func readUsers() throws {
   let query = "SELECT * FROM users"
   let results = try mysql.execute(query)
   for row in results {
       let id = row["id"] as! Int
       let name = row["name"] as! String
       let email = row["email"] as! String
       print("ID: \(id), Name: \(name), Email: \(email)")
   }
}
func updateUser(id: Int, name: String, email: String) throws {
   let query = "UPDATE users SET name = ?, email = ? WHERE id = ?"
   try mysql.execute(query, [name, email, id])
   print("User updated.")
}
func deleteUser(id: Int) throws {
   let query = "DELETE FROM users WHERE id = ?"
   try mysql.execute(query, [id])
   print("User deleted.")
}

Main Function:

do {
   try mysql.connect()
   var running = true
   while running {
       print("1. Create User")
       print("2. Read Users")
       print("3. Update User")
       print("4. Delete User")
       print("5. Exit")
       print("Enter your choice: ", terminator: "")
       
       if let choice = readLine(), let option = Int(choice) {
           switch option {
               case 1:
                   print("Enter name: ", terminator: "")
                   let name = readLine() ?? ""
                   print("Enter email: ", terminator: "")
                   let email = readLine() ?? ""
                   try createUser(name: name, email: email)
               case 2:
                   try readUsers()
               case 3:
                   print("Enter user ID: ", terminator: "")
                   let id = Int(readLine() ?? "") ?? 0
                   print("Enter new name: ", terminator: "")
                   let name = readLine() ?? ""
                   print("Enter new email: ", terminator: "")
                   let email = readLine() ?? ""
                   try updateUser(id: id, name: name, email: email)
               case 4:
                   print("Enter user ID: ", terminator: "")
                   let id = Int(readLine() ?? "") ?? 0
                   try deleteUser(id: id)
               case 5:
                   running = false
               default:
                   print("Invalid choice.")
           }
       }
   }
   try mysql.close()
} catch {
   print("Error: \(error)")
}

Compilation and Execution

Compile the Program:

Open the terminal and navigate to the project directory. Run the following command to build the project:

swift build

Run the Program:

./.build/debug/CRUDApp

This setup provides you with a basic terminal-based CRUD application using Swift and MySQL. The program allows you to create, read, update, and delete users from the database.