faq.yml 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. ---
  2. - "How do I do a database query?":
  3. - "I just want an array of the rows...": >-
  4. Use the Database#execute method. If you don't give it a block, it will
  5. return an array of all the rows:
  6. <pre>
  7. require 'sqlite3'
  8. db = SQLite3::Database.new( "test.db" )
  9. rows = db.execute( "select * from test" )
  10. </pre>
  11. - "I'd like to use a block to iterate through the rows...": >-
  12. Use the Database#execute method. If you give it a block, each row of the
  13. result will be yielded to the block:
  14. <pre>
  15. require 'sqlite3'
  16. db = SQLite3::Database.new( "test.db" )
  17. db.execute( "select * from test" ) do |row|
  18. ...
  19. end
  20. </pre>
  21. - "I need to get the column names as well as the rows...": >-
  22. Use the Database#execute2 method. This works just like Database#execute;
  23. if you don't give it a block, it returns an array of rows; otherwise, it
  24. will yield each row to the block. _However_, the first row returned is
  25. always an array of the column names from the query:
  26. <pre>
  27. require 'sqlite3'
  28. db = SQLite3::Database.new( "test.db" )
  29. columns, *rows = db.execute2( "select * from test" )
  30. # or use a block:
  31. columns = nil
  32. db.execute2( "select * from test" ) do |row|
  33. if columns.nil?
  34. columns = row
  35. else
  36. # process row
  37. end
  38. end
  39. </pre>
  40. - "I just want the first row of the result set...": >-
  41. Easy. Just call Database#get_first_row:
  42. <pre>
  43. row = db.get_first_row( "select * from table" )
  44. </pre>
  45. This also supports bind variables, just like Database#execute
  46. and friends.
  47. - "I just want the first value of the first row of the result set...": >-
  48. Also easy. Just call Database#get_first_value:
  49. <pre>
  50. count = db.get_first_value( "select count(*) from table" )
  51. </pre>
  52. This also supports bind variables, just like Database#execute
  53. and friends.
  54. - "How do I prepare a statement for repeated execution?": >-
  55. If the same statement is going to be executed repeatedly, you can speed
  56. things up a bit by _preparing_ the statement. You do this via the
  57. Database#prepare method. It returns a Statement object, and you can
  58. then invoke #execute on that to get the ResultSet:
  59. <pre>
  60. stmt = db.prepare( "select * from person" )
  61. 1000.times do
  62. stmt.execute do |result|
  63. ...
  64. end
  65. end
  66. stmt.close
  67. # or, use a block
  68. db.prepare( "select * from person" ) do |stmt|
  69. 1000.times do
  70. stmt.execute do |result|
  71. ...
  72. end
  73. end
  74. end
  75. </pre>
  76. This is made more useful by the ability to bind variables to placeholders
  77. via the Statement#bind_param and Statement#bind_params methods. (See the
  78. next FAQ for details.)
  79. - "How do I use placeholders in an SQL statement?": >-
  80. Placeholders in an SQL statement take any of the following formats:
  81. * @?@
  82. * @?_nnn_@
  83. * @:_word_@
  84. Where _n_ is an integer, and _word_ is an alpha-numeric identifier (or
  85. number). When the placeholder is associated with a number, that number
  86. identifies the index of the bind variable to replace it with. When it
  87. is an identifier, it identifies the name of the correponding bind
  88. variable. (In the instance of the first format--a single question
  89. mark--the placeholder is assigned a number one greater than the last
  90. index used, or 1 if it is the first.)
  91. For example, here is a query using these placeholder formats:
  92. <pre>
  93. select *
  94. from table
  95. where ( c = ?2 or c = ? )
  96. and d = :name
  97. and e = :1
  98. </pre>
  99. This defines 5 different placeholders: 1, 2, 3, and "name".
  100. You replace these placeholders by _binding_ them to values. This can be
  101. accomplished in a variety of ways.
  102. The Database#execute, and Database#execute2 methods all accept additional
  103. arguments following the SQL statement. These arguments are assumed to be
  104. bind parameters, and they are bound (positionally) to their corresponding
  105. placeholders:
  106. <pre>
  107. db.execute( "select * from table where a = ? and b = ?",
  108. "hello",
  109. "world" )
  110. </pre>
  111. The above would replace the first question mark with 'hello' and the
  112. second with 'world'. If the placeholders have an explicit index given, they
  113. will be replaced with the bind parameter at that index (1-based).
  114. If a Hash is given as a bind parameter, then its key/value pairs are bound
  115. to the placeholders. This is how you bind by name:
  116. <pre>
  117. db.execute( "select * from table where a = :name and b = :value",
  118. "name" => "bob",
  119. "value" => "priceless" )
  120. </pre>
  121. You can also bind explicitly using the Statement object itself. Just pass
  122. additional parameters to the Statement#execute statement:
  123. <pre>
  124. db.prepare( "select * from table where a = :name and b = ?" ) do |stmt|
  125. stmt.execute "value", "name" => "bob"
  126. end
  127. </pre>
  128. Or do a Database#prepare to get the Statement, and then use either
  129. Statement#bind_param or Statement#bind_params:
  130. <pre>
  131. stmt = db.prepare( "select * from table where a = :name and b = ?" )
  132. stmt.bind_param( "name", "bob" )
  133. stmt.bind_param( 1, "value" )
  134. # or
  135. stmt.bind_params( "value", "name" => "bob" )
  136. </pre>
  137. - "How do I discover metadata about a query?": >-
  138. If you ever want to know the names or types of the columns in a result
  139. set, you can do it in several ways.
  140. The first way is to ask the row object itself. Each row will have a
  141. property "fields" that returns an array of the column names. The row
  142. will also have a property "types" that returns an array of the column
  143. types:
  144. <pre>
  145. rows = db.execute( "select * from table" )
  146. p rows[0].fields
  147. p rows[0].types
  148. </pre>
  149. Obviously, this approach requires you to execute a statement that actually
  150. returns data. If you don't know if the statement will return any rows, but
  151. you still need the metadata, you can use Database#query and ask the
  152. ResultSet object itself:
  153. <pre>
  154. db.query( "select * from table" ) do |result|
  155. p result.columns
  156. p result.types
  157. ...
  158. end
  159. </pre>
  160. Lastly, you can use Database#prepare and ask the Statement object what
  161. the metadata are:
  162. <pre>
  163. stmt = db.prepare( "select * from table" )
  164. p stmt.columns
  165. p stmt.types
  166. </pre>
  167. - "I'd like the rows to be indexible by column name.": >-
  168. By default, each row from a query is returned as an Array of values. This
  169. means that you can only obtain values by their index. Sometimes, however,
  170. you would like to obtain values by their column name.
  171. The first way to do this is to set the Database property "results_as_hash"
  172. to true. If you do this, then all rows will be returned as Hash objects,
  173. with the column names as the keys. (In this case, the "fields" property
  174. is unavailable on the row, although the "types" property remains.)
  175. <pre>
  176. db.results_as_hash = true
  177. db.execute( "select * from table" ) do |row|
  178. p row['column1']
  179. p row['column2']
  180. end
  181. </pre>
  182. The other way is to use Ara Howard's
  183. "ArrayFields":http://rubyforge.org/projects/arrayfields
  184. module. Just require "arrayfields", and all of your rows will be indexable
  185. by column name, even though they are still arrays!
  186. <pre>
  187. require 'arrayfields'
  188. ...
  189. db.execute( "select * from table" ) do |row|
  190. p row[0] == row['column1']
  191. p row[1] == row['column2']
  192. end
  193. </pre>
  194. - "I'd like the values from a query to be the correct types, instead of String.": >-
  195. You can turn on "type translation" by setting Database#type_translation to
  196. true:
  197. <pre>
  198. db.type_translation = true
  199. db.execute( "select * from table" ) do |row|
  200. p row
  201. end
  202. </pre>
  203. By doing this, each return value for each row will be translated to its
  204. correct type, based on its declared column type.
  205. You can even declare your own translation routines, if (for example) you are
  206. using an SQL type that is not handled by default:
  207. <pre>
  208. # assume "objects" table has the following schema:
  209. # create table objects (
  210. # name varchar2(20),
  211. # thing object
  212. # )
  213. db.type_translation = true
  214. db.translator.add_translator( "object" ) do |type, value|
  215. db.decode( value )
  216. end
  217. h = { :one=>:two, "three"=>"four", 5=>6 }
  218. dump = db.encode( h )
  219. db.execute( "insert into objects values ( ?, ? )", "bob", dump )
  220. obj = db.get_first_value( "select thing from objects where name='bob'" )
  221. p obj == h
  222. </pre>
  223. - "How do insert binary data into the database?": >-
  224. Use blobs. Blobs are new features of SQLite3. You have to use bind
  225. variables to make it work:
  226. <pre>
  227. db.execute( "insert into foo ( ?, ? )",
  228. SQLite3::Blob.new( "\0\1\2\3\4\5" ),
  229. SQLite3::Blob.new( "a\0b\0c\0d ) )
  230. </pre>
  231. The blob values must be indicated explicitly by binding each parameter to
  232. a value of type SQLite3::Blob.
  233. - "How do I do a DDL (insert, update, delete) statement?": >-
  234. You can actually do inserts, updates, and deletes in exactly the same way
  235. as selects, but in general the Database#execute method will be most
  236. convenient:
  237. <pre>
  238. db.execute( "insert into table values ( ?, ? )", *bind_vars )
  239. </pre>
  240. - "How do I execute multiple statements in a single string?": >-
  241. The standard query methods (Database#execute, Database#execute2,
  242. Database#query, and Statement#execute) will only execute the first
  243. statement in the string that is given to them. Thus, if you have a
  244. string with multiple SQL statements, each separated by a string,
  245. you can't use those methods to execute them all at once.
  246. Instead, use Database#execute_batch:
  247. <pre>
  248. sql = <<SQL
  249. create table the_table (
  250. a varchar2(30),
  251. b varchar2(30)
  252. );
  253. insert into the_table values ( 'one', 'two' );
  254. insert into the_table values ( 'three', 'four' );
  255. insert into the_table values ( 'five', 'six' );
  256. SQL
  257. db.execute_batch( sql )
  258. </pre>
  259. Unlike the other query methods, Database#execute_batch accepts no
  260. block. It will also only ever return +nil+. Thus, it is really only
  261. suitable for batch processing of DDL statements.
  262. - "How do I begin/end a transaction?":
  263. Use Database#transaction to start a transaction. If you give it a block,
  264. the block will be automatically committed at the end of the block,
  265. unless an exception was raised, in which case the transaction will be
  266. rolled back. (Never explicitly call Database#commit or Database#rollback
  267. inside of a transaction block--you'll get errors when the block
  268. terminates!)
  269. <pre>
  270. database.transaction do |db|
  271. db.execute( "insert into table values ( 'a', 'b', 'c' )" )
  272. ...
  273. end
  274. </pre>
  275. Alternatively, if you don't give a block to Database#transaction, the
  276. transaction remains open until you explicitly call Database#commit or
  277. Database#rollback.
  278. <pre>
  279. db.transaction
  280. db.execute( "insert into table values ( 'a', 'b', 'c' )" )
  281. db.commit
  282. </pre>
  283. Note that SQLite does not allow nested transactions, so you'll get errors
  284. if you try to open a new transaction while one is already active. Use
  285. Database#transaction_active? to determine whether a transaction is
  286. active or not.
  287. #- "How do I discover metadata about a table/index?":
  288. #
  289. #- "How do I do tweak database settings?":