statement.go 2.0 KB

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