→.NETプログラミング
→データベース関連
Tips †
- SqlCommandのパラメータとOleDbCommandのパラメータの渡し方は微妙に違うので注意
- SqlCommandの場合
- プレースホルダは "@xxx"とし、SqlParameterの名前にも"@xxx"を渡す
- OleDbCommandの場合
- プレースホルダは "?" とし、OleDbParameterの名前にはフィールド名を渡す
- OleDbCommandに対してSqlCommandのやり方でパラメータを渡すと「スカラ変数@xxxを宣言してください」というメッセージのエラーになる。
- DataSetのDataRowからカラム名(列名、フィールド名)を取得するには
- row.Table.Columns[i].ColumnNameを参照する
- SqlConnectionで接続プールをオフにするには接続文字列に "Pooling=false;"を追加する。
- SqlConnectionはOleDbConnectionとは微妙に違うので注意
- 更新系SQLを文字列編集の際の注意
- こういうコードを書いたらダメ
void LogUserName(SqlConnection conn, string userName) {
string sqlText = "insert user_names values('" + userName + "')";
SqlCommand cmd = new SqlCommand(sqlText, conn);
cmd.ExecuteNonQuery();
}
- userNameに何が入ってくるかわからないから(いわゆるSQLインジェクションの危険性)
- 例えば 名前','その隣の項目に入れたい値 という文字列が来るとか。
- パラメータを使うこと
void LogUserName(SqlConnection conn, string userName) {
string sqlText = "insert user_names values(@n)";
SqlCommand cmd = new SqlCommand(sqlText, conn);
SqlParameter p = cmd.Parameters.Add("@n", SqlDbType.VarChar, userName.Length);
p.Value = userName;
cmd.ExecuteNonQuery();
}
- SqlCommandの例外を拾うときはSqlExceptionでやった方が多少細かく情報が取れます
パフォーマンス †
SQL Serverに接続すると General network error. Check your network documentation. というエラーになる †
- OLE DBで無効なコネクションがプールされることから起きる模様
- こちらを参照:http://support.microsoft.com/?scid=kb%3Ben-us%3B229564&x=15&y=8
- CAUSE
In the current design, after an application role is enabled on a client connection to SQL Server,
you cannot reset the security context of that connection. Therefore, when the user ends
the SQL Server session and disconnects from the server, the session is not reusable.
However, OLE DB resource pooling returns the closed connection to the pool,
and the error occurs when that connection is reused and the client application tries to reset
the connection's security context by calling sp_setapprole again.
- ただし、SQLConnectionクラスを使ってる場合、"OLE DB Services"というパラメータ自体受け付けてくれない。"Pooling=false"というのがそれに当たる模様
その他 †
- ADO.NET 2.0の接続文字列の管理問題 2007.7.16
- .NET 2.0では接続文字列の管理場所がappSettings要素からconnectionStrings要素へ移動してしまったので、user.configで環境ごとの設定を持つことができなくなってしまいました。
|