五种典型语句:
1.create table temp(cola int);
2.delete from emp where empno:=7788;
3.delete from empwhere empno=:no;
4.select ename from emp where empno=:no;
5 select :a,:b from :c where empno=:no;
动态SQL二可以出来前三种,也就是SQL语句中有了变量,但变量仅仅只在右边,等号的右边。
使用方式是用Prepare来组织SQL语句,然后EXECUTE sql_statement USING :变量值
上例子:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sqlca.h>
void connect();
void sql_err();
void dynamic_sqltwo();
void main()
{
EXEC SQL WHENEVER SQLERROR DO sql_err();
connect();
dynamic_sqltwo();
EXEC SQL COMMIT RELEASE;
}
void sql_err()
{
printf("%.*s\n",sqlca.sqlerrm.sqlerrml,,sqlca.sqlerrm.sqlerrmc);
}
void connect()/*数据库连接-本地数据库,不添加server*/
{
EXEC SQL BEGIN DECLARE SECTION;
char username[20],password[20];
EXEC SQL END DECLARE SECTION;
printf("input username: ");
gets(username);
printf("input password: ");
gets(password);
EXEC SQL CONNECT :username IDENTIFIED BY :password;
}
void dynamic_sqltwo()
{
EXEC SQL BEGIN DECLARE SECTION;
char name[10];
int newsalary;
char control;
EXEC SQL END DECLARE SECTION;
for(;;)
{
printf("intput employee name: ");
gets(name);
printf("input employee salary: ");
scanf("%d",&newsalary);
getchar();
EXEC SQL PREPARE stat FROM 'UPDATE emp SET sal=:a WHERE upper(ename)=upper(:b)';
EXEC SQL EXECUTE stat USING :newsalary,:name;
printf("continue? (Y/N)");
scanf("%c",&control);
getchar();
if(control=='N'||control=='n') break;
}
}
看结果
这里注意当用的表不是emp表的时候有如下情况会发生!!!!
描述:
两种创建表的方式
create table tt(SAL number(7,2),ENAME varchar2(10));
create table ss as select sal,ename from emp;
emp表机构如下
ENAME VARCHAR2(10)
SAL NUMBER(7,2)
问题:
我的proc程序可以操作ss表
但是对tt表(自己定义的)却没办法修改
proc代码如下:当使用的时候修改表名,分别用ss,tt!
void dynamic_sqltwo()
{
EXEC SQL BEGIN DECLARE SECTION;
char name[10];
int newsalary;
char control;
EXEC SQL END DECLARE SECTION;
for(;;)
{
printf("intput employee name: ");
gets(name);
printf("input employee salary: ");
scanf("%d",&newsalary);
getchar();
EXEC SQL PREPARE stat FROM 'UPDATE tt SET sal=:a WHERE upper(ename)=upper(:b)';
EXEC SQL EXECUTE stat USING :newsalary,:name;
printf("continue? (Y/N)");
scanf("%c",&control);
getchar();
if(control=='N'||control=='n') break;
}
}
虽说对数据类型要求很严格但是,我的数据类型一样呀
这个时候,将新建的表ss的sal类型修改为number(10),就好了!!!!很奇怪,原因原来是:创建表的时候,并没有commit,所以并没有存到硬盘文件!!!