statement.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. errLog.Print(ErrInvalidConn)
  21. return driver.ErrBadConn
  22. }
  23. err := stmt.mc.writeCommandPacketUint32(comStmtClose, stmt.id)
  24. stmt.mc = nil
  25. return err
  26. }
  27. func (stmt *mysqlStmt) NumInput() int {
  28. return stmt.paramCount
  29. }
  30. func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) {
  31. if stmt.mc.netConn == nil {
  32. errLog.Print(ErrInvalidConn)
  33. return nil, driver.ErrBadConn
  34. }
  35. // Send command
  36. err := stmt.writeExecutePacket(args)
  37. if err != nil {
  38. return nil, err
  39. }
  40. mc := stmt.mc
  41. mc.affectedRows = 0
  42. mc.insertId = 0
  43. // Read Result
  44. resLen, err := mc.readResultSetHeaderPacket()
  45. if err == nil {
  46. if resLen > 0 {
  47. // Columns
  48. err = mc.readUntilEOF()
  49. if err != nil {
  50. return nil, err
  51. }
  52. // Rows
  53. err = mc.readUntilEOF()
  54. }
  55. if err == nil {
  56. return &mysqlResult{
  57. affectedRows: int64(mc.affectedRows),
  58. insertId: int64(mc.insertId),
  59. }, nil
  60. }
  61. }
  62. return nil, err
  63. }
  64. func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) {
  65. if stmt.mc.netConn == nil {
  66. errLog.Print(ErrInvalidConn)
  67. return nil, driver.ErrBadConn
  68. }
  69. // Send command
  70. err := stmt.writeExecutePacket(args)
  71. if err != nil {
  72. return nil, err
  73. }
  74. mc := stmt.mc
  75. // Read Result
  76. resLen, err := mc.readResultSetHeaderPacket()
  77. if err != nil {
  78. return nil, err
  79. }
  80. rows := new(binaryRows)
  81. rows.mc = mc
  82. if resLen > 0 {
  83. // Columns
  84. // If not cached, read them and cache them
  85. if stmt.columns == nil {
  86. rows.columns, err = mc.readColumns(resLen)
  87. stmt.columns = rows.columns
  88. } else {
  89. rows.columns = stmt.columns
  90. err = mc.readUntilEOF()
  91. }
  92. }
  93. return rows, err
  94. }