statements can count parameters

This commit is contained in:
Aaron Patterson 2010-07-07 09:47:41 -07:00
parent 2ad51dcac2
commit a5d8a087a7
2 changed files with 23 additions and 2 deletions

View File

@ -9,7 +9,6 @@ VALUE cMysql2Statement;
static VALUE prepare(VALUE self, VALUE sql) static VALUE prepare(VALUE self, VALUE sql)
{ {
MYSQL_STMT * stmt; MYSQL_STMT * stmt;
Data_Get_Struct(self, MYSQL_STMT, stmt); Data_Get_Struct(self, MYSQL_STMT, stmt);
if(mysql_stmt_prepare(stmt, StringValuePtr(sql), RSTRING_LEN(sql))) { if(mysql_stmt_prepare(stmt, StringValuePtr(sql), RSTRING_LEN(sql))) {
@ -19,9 +18,22 @@ static VALUE prepare(VALUE self, VALUE sql)
return self; return self;
} }
/* call-seq: stmt.param_count # => 2
*
* Returns the number of parameters the prepared statement expects.
*/
static VALUE param_count(VALUE self)
{
MYSQL_STMT * stmt;
Data_Get_Struct(self, MYSQL_STMT, stmt);
return ULL2NUM(mysql_stmt_param_count(stmt));
}
void init_mysql2_statement() void init_mysql2_statement()
{ {
cMysql2Statement = rb_define_class_under(mMysql2, "Statement", rb_cObject); cMysql2Statement = rb_define_class_under(mMysql2, "Statement", rb_cObject);
rb_define_method(cMysql2Statement, "prepare", prepare, 1); rb_define_method(cMysql2Statement, "prepare", prepare, 1);
rb_define_method(cMysql2Statement, "param_count", param_count, 0);
} }

View File

@ -2,7 +2,7 @@
require 'spec_helper' require 'spec_helper'
describe Mysql2::Statement do describe Mysql2::Statement do
before :all do before :each do
@client = Mysql2::Client.new :host => "localhost", :username => "root" @client = Mysql2::Client.new :host => "localhost", :username => "root"
end end
@ -26,4 +26,13 @@ describe Mysql2::Statement do
@client.close @client.close
lambda { stmt.prepare 'SELECT 1' }.should raise_error(Mysql2::Error) lambda { stmt.prepare 'SELECT 1' }.should raise_error(Mysql2::Error)
end end
it "should tell us the param count" do
stmt = @client.create_statement
stmt.prepare 'SELECT ?, ?'
stmt.param_count.should == 2
stmt.prepare 'SELECT 1'
stmt.param_count.should == 0
end
end end