Component index
Section index

Component sql_query


Search

	/*
	    Managing records in SQL database is often cumbersome. You end up
	    with complex insert or update statement, with many fields. It is
	    easy to get it wrong, mixing fields and so on.
	
	    A "name" safe solution is needed. Using the sqlgen_interface utility
	    one may create class definitions suitable to solve this. You can
	    either create a class definition "by hand" or by extracting definitions
	    from a database. The later is generally used. The goal is to produce
	    a C++ include file. For example, using the sample database created
	    by sample_table.sh, one will do
	
	    sqlgen_interface --prefix --database sample test >sample.h
	
	    where sample is the database name and test is one table.
	*/
	<mod>
	static void sample_sqlgen_interface()
	{
	    query_setdefaultdb ("localhost","sample");
	    // Here is a sample query using a  safe interface
	    <call sql_query>("select * from test");
	    <f onerow>
	        C_test rec;
	        rec.set (fields,row);
	        printf ("record %03d: name=%s address=%s telephone=%s age=%d\n"
	            ,rownum
	            ,rec.name.get(),rec.address.get(),rec.telephone.get(),rec.age.getval());
	    </f>
	    </call>
	
	    // Do some updates. We will change the phone number for member jack
	    <glocal>
	        C_test rec;
	    </glocal>
	    <call sql_query>("select * from test where name='jack'");
	    <f onerow>
	        glocal.rec.set (fields,row);
	    </f>
	    </call>
	    // We change a field
	    glocal.rec.telephone.setfrom ("666-7777");
	    // Only the changed field will be updated.
	    glocal.rec.update("test","name='%s'","jack");
	}
	</mod>