Embedded SQL is a method of combining the computing power of a programming language with the database query capabilities of SQL (Structured Query Language). This integration allows developers to write SQL commands directly within the code of a host programming language, such as C, C++, Java, or COBOL. This approach simplifies database operations by enabling the seamless execution of SQL queries from within the host program.
Here's a simple example to demonstrate embedded SQL in a C program:
#include <stdio.h>
#include <sqlca.h> // Include the SQL Communications Area header
int main() {
EXEC SQL BEGIN DECLARE SECTION;
char username[20];
char password[20];
EXEC SQL END DECLARE SECTION;
// Assign values to host variables
strcpy(username, "admin");
strcpy(password, "password123");
// Connect to the database
EXEC SQL CONNECT TO mydatabase USER :username IDENTIFIED BY :password;
if (sqlca.sqlcode != 0) {
printf("Connection failed: %s\\\\n", sqlca.sqlerrm.sqlerrmc);
return 1;
}
// Execute a query
EXEC SQL SELECT COUNT(*) INTO :count FROM users;
// Disconnect from the database
EXEC SQL DISCONNECT;
printf("Number of users: %d\\\\n", count);
return 0;
}