Sabtu, 17 April 2010

Cpp bdakses

#include
#include
#include

using namespace std;

/*namespace untuk menangani error*/
namespace exception{
struct error{
const char *p;
error(const char *q){
p = q;
}
};
}

int main(){

MYSQL mysql,*sock; // handle untuk mysql
MYSQL_RES *res; // menyimpan hasil eksekusi query
MYSQL_ROW row; // menyimpan satu rekaman
int state; // menyimpan kembalian eksekusi query
char *host = "localhost";
char *user = "root";
char *password = "root";
char *dbName = "kuliah";

try{
// menginisialisasi variabel global MySQL
mysql_init(&mysql);
// membuat koneksi MySQL dan basis data
if (!(sock = mysql_real_connect(&mysql, host, user, password, dbName, 0, NULL, 0))){
throw exception::error("Koneksi MySQL gagal\n");
}

mysql.reconnect= 1;

// eksekusi query
state = mysql_query(sock, "SELECT * FROM mahasiswa");

if( state != 0 ) {
throw exception::error("Eksekusi query gagal\n");
}

// ambil hasil query
res = mysql_store_result (sock);

int i = 1;
while((row = mysql_fetch_row(res)) != NULL){
// cetak hasil query

printf("-----------------------\n");
printf("record ke : %d\n", i);
printf("nim : %s\n", (row[0] ? row[0] : "NULL"));
printf("nama : %s\n", (row[1] ? row[1] : "NULL"));
printf("tanggal lahir : %s\n", (row[2] ? row[2] : "NULL"));
printf("alamat : %s\n", (row[3] ? row[3] : "NULL"));
printf("-----------------------\n");
i = i + 1;
}

mysql_free_result(res);
mysql_close(sock);

}
catch(exception::error e){
printf("%s\n", e.p);
}

return 0;
}