Fix for Bug : 2410115
[csql.git] / examples / dbapi / manDBAPIinsert.c
blobc870d3b3e7e165c84a8e1b0cd5bbaecaf9a64ee0
1 // DBAPI Demo: insert and read
2 //
4 #include<CSql.h>
5 int main()
7 // Connect to the database
8 Connection conn;
9 DbRetVal rv = conn.open("root", "manager");
10 if (rv != OK) return 1;
12 // get database manager
13 DatabaseManager *dbMgr = conn.getDatabaseManager();
14 if (dbMgr == NULL) { printf("Auth failed\n"); return 2;}
16 //Define the table
17 TableDef tabDef;
18 tabDef.addField("empId", typeInt, 0, NULL, true);
19 tabDef.addField("name", typeString, 20);
20 tabDef.addField("salary", typeFloat);
22 // create table
23 rv = dbMgr->createTable("EMP", tabDef);
24 if (rv != OK) { printf("Table creation failed\n"); conn.close(); return 3; }
25 printf("Table created\n");
26 HashIndexInitInfo *idxInfo = new HashIndexInitInfo();
27 strcpy(idxInfo->tableName, "EMP");
28 idxInfo->list.append("empId");
29 idxInfo->isUnique = true;
30 idxInfo->isPrimary = true;
31 idxInfo->indType = hashIndex;
32 rv = dbMgr->createIndex("indx1", idxInfo);
33 if (rv != OK) { printf("Index creation failed\n"); return ErrUnknown; }
35 // open table
36 Table *table = dbMgr->openTable("EMP");
37 if (table == NULL)
39 printf("Unable to open table\n");
40 dbMgr->dropTable("EMP");
41 conn.close();
42 return -1;
45 // allocate fields to bind
46 int id1 = 0;
47 char *setNames[10] = {"Praba", "Kishor", "Jiten", "Gopal", "Aruna", "Ravi", "Kiran" , "Sanjay", "Rajesh", "Arun" };
48 float sal=0.0;
49 char name[20];
50 int icount =0, i = 0;
52 // bind the allocated fields
53 table->bindFld("empId", &id1);
54 table->bindFld("name", name);
55 table->bindFld("salary", &sal);
57 // start transaction
58 conn.startTransaction();
59 for (i = 0 ; i < 10; i++)
61 // set values to insert into table
62 id1 = 1001 + i;
63 sal = 1000.00 * (i + 1);
64 strcpy(name, setNames[i]);
66 // insert tuple
67 rv = table->insertTuple();
68 if (rv != OK) break;
70 // commit transaction
71 conn.commit();
72 printf("%d Tuples inserted\n", i);
74 // start transaction
75 conn.startTransaction();
77 // set condition to select all the tuples
78 table->setCondition(NULL);
79 rv = table->execute();
80 if (rv != OK)
82 dbMgr->closeTable(table);
83 dbMgr->dropTable("EMP");
84 conn.close();
86 printf("\ninserted values are as follows\n");
87 printf("EmpId | name\t| salary\n");
88 printf("--------------------------\n");
89 i = 0;
90 while(true)
92 // fetch each tuple satisfying the condition
93 char * tuple = (char*)table->fetch();
94 if (tuple == NULL) {break;}
95 printf("%d | %s\t| %6.2f\n", id1, name, sal);
96 i++;
98 // commit the transaction
99 conn.commit();
101 //close the condition
102 table->close();
104 // close the table using the table handle
105 dbMgr->closeTable(table);
107 //close the connection
108 conn.close();
109 return 0;