statement.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public
  6. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  7. // You can obtain one at http://mozilla.org/MPL/2.0/.
  8. package mysql
  9. import (
  10. "database/sql/driver"
  11. )
  12. type mysqlStmt struct {
  13. mc *mysqlConn
  14. id uint32
  15. paramCount int
  16. columns []mysqlField // cached from the first query
  17. }
  18. func (stmt *mysqlStmt) Close() error {
  19. if stmt.mc == nil || stmt.mc.netConn == nil {
  20. return errInvalidConn
  21. }
  22. err := stmt.mc.writeCommandPacketUint32(comStmtClose, stmt.id)
  23. if stmt.columns != nil {
  24. putFields(stmt.columns)
  25. stmt.columns = nil
  26. }
  27. stmt.mc = nil
  28. return err
  29. }
  30. func (stmt *mysqlStmt) NumInput() int {
  31. return stmt.paramCount
  32. }
  33. func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) {
  34. // Send command
  35. err := stmt.writeExecutePacket(args)
  36. if err != nil {
  37. return nil, err
  38. }
  39. mc := stmt.mc
  40. mc.affectedRows = 0
  41. mc.insertId = 0
  42. // Read Result
  43. resLen, err := mc.readResultSetHeaderPacket()
  44. if err == nil {
  45. if resLen > 0 {
  46. // Columns
  47. err = mc.readUntilEOF()
  48. if err != nil {
  49. return nil, err
  50. }
  51. // Rows
  52. err = mc.readUntilEOF()
  53. }
  54. if err == nil {
  55. return &mysqlResult{
  56. affectedRows: int64(mc.affectedRows),
  57. insertId: int64(mc.insertId),
  58. }, nil
  59. }
  60. }
  61. return nil, err
  62. }
  63. func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) {
  64. // Send command
  65. err := stmt.writeExecutePacket(args)
  66. if err != nil {
  67. return nil, err
  68. }
  69. mc := stmt.mc
  70. // Read Result
  71. resLen, err := mc.readResultSetHeaderPacket()
  72. if err != nil {
  73. return nil, err
  74. }
  75. rows := newMysqlRows()
  76. rows.mc = stmt.mc
  77. rows.binary = true
  78. if resLen > 0 {
  79. // Columns
  80. // If not cached, read them and cache them
  81. if stmt.columns == nil {
  82. rows.columns, err = mc.readColumns(resLen)
  83. stmt.columns = rows.columns
  84. } else {
  85. rows.columns = stmt.columns
  86. err = mc.readUntilEOF()
  87. }
  88. }
  89. return &mysqlRowsI{rows}, err
  90. }