MySQL Vala 编程示例

vala是专为gnome环境准备的开发语言,之所以vala会出现,是因为目前的glib,gio,gtk+,gnome-lib等等的C语言接口开发 起来实在太繁琐(这个深有感触),而同时,如果采用java,C++这些东西,那又显得太臃肿。

[C/C++]代码

using Mysql;

int main (string[] args)
{

  int rc = 0;

  ClientFlag cflag    = 0;
  string     host     = "127.0.0.1";
  string     user     = "root";
  string     password = "";
  string     database = "test";
  int        port     = 3306;
  string     socket   = null;

  Database mysql = new Mysql.Database ();

  var isConnected = mysql.real_connect(host, user, password, database, port, socket, cflag);

  if ( ! isConnected ) {

    rc = 1;
    stdout.printf("ERROR %u: Connection failed: %s\n", mysql.errno(), mysql.error());
    return rc;
  }

  stdout.printf("Connected to MySQL server version: %s (%lu)\n"
              , mysql.get_server_info()
              , (ulong) mysql.get_server_version());

  string sql = "SELECT * FROM test LIMIT 10";
  rc = mysql.query(sql);
  if ( rc != 0 ) {

    stdout.printf("ERROR %u: Query failed: %s\n", mysql.errno(), mysql.error());
    return rc;
  }

  Result ResultSet = mysql.use_result();

  string[] MyRow;

  while ( (MyRow = ResultSet.fetch_row()) != null ) {

    stdout.printf("id: %s | data: %s | ts: %s\n", MyRow[0], MyRow[1], MyRow[2]);
  }
  // free_result is called automatically

  // mysql_close is called automatically
  return rc;
}
安装 Vala
sudo apt-key adv --recv-keys --keyserver keyserver.Ubuntu.com 7DAAC99C
sudo add-apt-repository ppa:vala-team
sudo apt-get update
sudo apt-get install valac vala-utils vala-doc valac-dbg
valac --version

sudo apt-get install libgee-dev 
sudo apt-get install gedit-vala-plugin vala-gen-project
sudo apt-get install valide
 
编译方法
 
valac --pkg=mysql --Xcc=-lmysqlclient mysql_ex1.vala --Xcc=-I/home/mysql/src/mysql-5.1.55 \
      --Xcc=-L/home/mysql/product/mysql-5.1.55/lib -v

相关推荐