fc2ブログ

データの生成(create)

データ生成(新規作成)のSQLとコードは、次のようになります。
スポンサーリンク

  Const GET_MARKET_ID_SQL As String = " (select market_id from t_market where market_name = :market_name) "

Const GET_CATEGORY_ID_SQL As String = " (select category_id from t_category where category_name = :category_name) "

Const GET_ITEM_ID_SQL As String = " (select item_id from t_item where category_id = " & GET_CATEGORY_ID_SQL & " and item_name = :item_name) "

Const SET_VALUE_SQL As String = "insert into t_value (term, company_id, market_id, datetime, category_id, item_id, value) " & _
"values (:term, :company_id, " & GET_MARKET_ID_SQL & ", :datetime, " & GET_CATEGORY_ID_SQL & ", " & GET_ITEM_ID_SQL & ", :value);"

Protected _createCom As NpgsqlCommand
Public Property CreateCom As NpgsqlCommand
Set(ByVal value As NpgsqlCommand)
_createCom = value
End Set
Get
Return _createCom
End Get
End Property

Protected _tx As NpgsqlTransaction
Public ReadOnly Property Tx As NpgsqlTransaction
Get
Return _tx
End Get
End Property

Sub BeginTx()
_tx = _conn.BeginTransaction()
_createCom = New NpgsqlCommand(SET_VALUE_SQL, _conn, _tx)
InitCreateUpdate(_createCom)
End Sub

Sub CommitTx()
_tx.Commit()
End Sub

Private Sub InitCreateUpdate(ByVal command As NpgsqlCommand)
command.Parameters.Add(New NpgsqlParameter("term", DbType.String))
command.Parameters.Add(New NpgsqlParameter("company_id", DbType.Int32))
command.Parameters.Add(New NpgsqlParameter("market_name", DbType.String))
command.Parameters.Add(New NpgsqlParameter("datetime", DbType.DateTime))
command.Parameters.Add(New NpgsqlParameter("category_name", DbType.String))
command.Parameters.Add(New NpgsqlParameter("item_name", DbType.String))
command.Parameters.Add(New NpgsqlParameter("value", DbType.Double))
command.Prepare()
End Sub

Sub Create(ByVal sv As SeqValue)
CreateUpdate(_createCom, sv)
End Sub

Private Shared Sub CreateUpdate(ByVal command As NpgsqlCommand, ByVal sv As SeqValue)
command.Parameters("term").Value = sv.term
command.Parameters("company_id").Value = sv.company_id
command.Parameters("market_name").Value = sv.market.DBItemName
command.Parameters("datetime").Value = sv.datetime
command.Parameters("category_name").Value = sv.category_name
command.Parameters("item_name").Value = sv.item_name
command.Parameters("value").Value = sv.value
command.ExecuteNonQuery()
End Sub
SQLの:(コロン)で始まる「:XXXX」は、SQLにパラメータとして与えられるようにした表現です。コード内ではInitCreateUpdateメソッドで、型の定義付けを行っています。なお、SeqValueクラスは、t_valueテーブルのEntityクラスです。
上のクラスを呼び出す側は次のコードのようにします。


Dim dao As New SeqValueDAO
dao.BeginTx()
dao.Create(seqValue1)
dao.Create(seqValue2)
dao.Create(seqValue3)
' ・・・
dao.CommitTx()
SeqValueDAO#BeginTxでデータベース更新の準備(トランザクションの開始)をします。SeqValueDAO#CreateでSQLを実行します。最後に、SeqValueDAO#CommitTxでコミットしています。

検索ワード:SQL、insert、プリペアードステートメント、トランザクション、コミット



スポンサーリンク
<<データベース接続 | ホーム | データの読み出し(read)>>
コメント(0)
コメントの投稿
トラックバック(0)