荒木敦
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: Configuring and using JDBC robots: noindex, noarchive --- https://www.playframework.com/documentation/2.6.x/ScalaDatabase # Accessing an SQL database SQLデータベースへのアクセス # Configuring JDBC connection pools JDBC接続プールの設定 Play provides a plug-in for managing JDBC connection pools. You can configure as many databases as you need. Playには、JDBC接続プールを管理するためのプラグインが用意されています。 必要な数のデータベースを構成できます。 To enable the database plug-in, add jdbc in your build dependencies : データベース・プラグインを使用可能にするには、ビルドの依存関係にjdbcを追加します。 ``` libraryDependencies += jdbc ``` Then you must configure a connection pool in the conf/application.conf file. By convention, the default JDBC data source must be called default and the corresponding configuration properties are db.default.driver and db.default.url. 次に、conf/application.confファイルに接続プールを設定する必要があります。 慣例として、デフォルトのJDBCデータソースはデフォルトと呼ばれ、対応する設定プロパティはdb.default.driverとdb.default.urlです。 If something isn’t properly configured you will be notified directly in your browser: 何かが正しく構成されていない場合は、ブラウザで直接通知されます。 ![](https://i.imgur.com/y9iULPI.png) Note: You likely need to enclose the JDBC URL configuration value with double quotes, since ‘:’ is a reserved character in the configuration syntax. 注意:JDBC URL設定値を二重引用符で囲む必要があります。これは、 ':'は設定構文の予約文字です。 # H2 database engine connection properties H2データベースエンジン接続プロパティ In memory database: インメモリデータベース: ``` # Default database configuration using H2 database engine in an in-memory mode # インメモリーモードでH2データベース・エンジンを使用するデフォルトのデータベース構成 db.default.driver=org.h2.Driver db.default.url="jdbc:h2:mem:play" ``` File based database: ファイルベースのデータベース ``` # Default database configuration using H2 database engine in a persistent mode # 永続モードでH2データベースエンジンを使用するデフォルトのデータベース構成 db.default.driver=org.h2.Driver db.default.url="jdbc:h2:/path/to/db-file" ``` The details of the H2 database URLs are found from [H2 Database Engine Cheat Sheet](http://www.h2database.com/html/cheatSheet.html). H2データベースのURLの詳細は、[H2データベースエンジンのチートシート](http://www.h2database.com/html/cheatSheet.html)から検索されます。 # SQLite database engine connection properties SQLiteデータベースエンジンの接続プロパティ ``` # Default database configuration using SQLite database engine db.default.driver=org.sqlite.JDBC db.default.url="jdbc:sqlite:/path/to/db-file" ``` # PostgreSQL database engine connection properties PostgreSQL データベースエンジンの接続プロパティ ``` # Default database configuration using PostgreSQL database engine db.default.driver=org.postgresql.Driver db.default.url="jdbc:postgresql://database.example.com/playdb" ``` # MySQL database engine connection properties MySQL データベースエンジンの接続プロパティ ``` # Default database configuration using MySQL database engine # Connect to playdb as playdbuser db.default.driver=com.mysql.jdbc.Driver db.default.url="jdbc:mysql://localhost/playdb" db.default.username=playdbuser db.default.password="a strong password" ``` # How to configure several data sources 複数のデータソースを構成する方法 ``` # Orders database db.orders.driver=org.h2.Driver db.orders.url="jdbc:h2:mem:orders" # Customers database db.customers.driver=org.h2.Driver db.customers.url="jdbc:h2:mem:customers" ``` # Exposing the datasource through JNDI JNDIを介してデータソースを公開する Some libraries expect to retrieve the Datasource reference from JNDI. 一部のライブラリでは、JNDIからDatasource参照を取得することを想定しています。 You can expose any Play managed datasource via JNDI by adding this configuration in conf/application.conf: conf/application.conf に次の設定を追加することで、JNDI経由でPlay管理データソースを公開することができます。 ``` db.default.driver=org.h2.Driver db.default.url="jdbc:h2:mem:play" db.default.jndiName=DefaultDS ``` # How to configure SQL log statement SQLログステートメントの設定方法 Not all connection pools offer (out of the box) a way to log SQL statements. HikariCP, per instance, suggests that you use the log capacities of your database vendor. From [HikariCP docs](https://github.com/brettwooldridge/HikariCP/tree/dev#log-statement-text--slow-query-logging): すべての接続プールがSQL文を記録する方法を提供しているわけではありません。 インスタンスごとのHikariCPは、データベースベンダーのログ容量を使用することを示唆しています。 [HikariCPのドキュメント](https://github.com/brettwooldridge/HikariCP/tree/dev#log-statement-text--slow-query-logging)から: ## Log Statement Text / Slow Query Logging ログステートメントテキスト/スロークエリロギング Like Statement caching, most major database vendors support statement logging through properties of their own driver. This includes Oracle, MySQL, Derby, MSSQL, and others. Some even support slow query logging. We consider this a “development-time” feature. For those few databases that do not support it, jdbcdslog-exp is a good option. Great stuff during development and pre-Production. ステートメントキャッシングと同様に、大部分の主要データベースベンダーは、独自のドライバのプロパティを使用してステートメントログをサポートしています。 これには、Oracle、MySQL、Derby、MSSQLなどが含まれます。 クエリのロギングが遅いものもあります。 これを「開発時」の機能とみなします。 Jdbcdslog-expをサポートしていないデータベースのほうが良い選択です。 開発中と製造前に素晴らしいもの。 Because of that, Play uses jdbcdslog-exp to enable consistent SQL log statement support for supported pools. The SQL log statement can be configured by database, using logSql property: そのため、Playはjdbcdslog-expを使用して、サポートされているプールに対する一貫したSQLログ文のサポートを可能にします。 SQLのlog文は、logSqlプロパティを使用してデータベースで設定できます。 ``` # Default database configuration using PostgreSQL database engine db.default.driver=org.postgresql.Driver db.default.url="jdbc:postgresql://database.example.com/playdb" db.default.logSql=true ``` After that, you can configure the jdbcdslog-exp log level as explained in their manual. Basically, you need to configure your root logger to INFO and then decide what jdbcdslog-exp will log (connections, statements and result sets). Here is an example using logback.xml to configure the logs: その後、jdbcdslog-expログレベルをマニュアルの説明に従って設定することができます。 基本的には、ルート・ロガーをINFOに構成し、jdbcdslog-expが記録するもの(接続、文および結果セット)を決定する必要があります。 logback.xmlを使用してログを設定する例を次に示します。 ``` scala <!-- ~ Copyright (C) 2009-2016 Lightbend Inc. <https://www.lightbend.com> --> <!-- The default logback configuration that Play uses if no other configuration is provided --> <configuration> <conversionRule conversionWord="coloredLevel" converterClass="play.api.libs.logback.ColoredLevel" /> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${application.home:-.}/logs/application.log</file> <encoder> <pattern>%date [%level] from %logger in %thread - %message%n%xException</pattern> </encoder> </appender> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%coloredLevel %logger{15} - %message%n%xException{10}</pattern> </encoder> </appender> <appender name="ASYNCFILE" class="ch.qos.logback.classic.AsyncAppender"> <appender-ref ref="FILE" /> </appender> <appender name="ASYNCSTDOUT" class="ch.qos.logback.classic.AsyncAppender"> <appender-ref ref="STDOUT" /> </appender> <logger name="play" level="INFO" /> <logger name="application" level="DEBUG" /> <logger name="org.jdbcdslog.ConnectionLogger" level="OFF" /> <!-- Won' log connections --> <logger name="org.jdbcdslog.StatementLogger" level="INFO" /> <!-- Will log all statements --> <logger name="org.jdbcdslog.ResultSetLogger" level="OFF" /> <!-- Won' log result sets --> <root level="WARN"> <appender-ref ref="ASYNCFILE" /> <appender-ref ref="ASYNCSTDOUT" /> </root> </configuration> ``` Warning: Keep in mind that this is intended to be used just in development environments and you should not configure it in production, since there is a performance degradation and it will pollute your logs. 警告:これは開発環境でのみ使用することを目的としており、パフォーマンスが低下してログを汚染するため、本番環境では設定しないでください。 # Configuring the JDBC Driver dependency JDBCドライバの依存関係のコンフィグレーション Play is bundled only with an H2 database driver. Consequently, to deploy in production you will need to add your database driver as a dependency. PlayはH2データベースドライバのみでバンドルされています。 したがって、本番環境でデプロイするには、データベース・ドライバを依存関係として追加する必要があります。 For example, if you use MySQL5, you need to add a dependency for the connector: たとえば、MySQL5を使用する場合は、コネクターに依存関係を追加する必要があります。 ``` libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.36" ``` Or if the driver can’t be found from repositories you can drop the driver into your project’s unmanaged dependencies lib directory. または、ドライバがリポジトリから見つからない場合、ドライバをプロジェクトのアンマネージ依存ライブラリのlibディレクトリにドロップすることができます。 # Obtaining a JDBC connection JDBC接続の取得 There are several ways to retrieve a JDBC connection. The following code show you a JDBC example very simple, working with MySQL 5.*: JDBC接続を取得する方法はいくつかあります。 次のコードは、MySQL 5で動作する非常にシンプルなJDBCの例を示しています。*: ``` scala package scalaguide.sql import javax.inject.Inject import play.api.Play.current import play.api.mvc._ import play.api.db._ class ScalaControllerInject @Inject()(db: Database) extends Controller { def index = Action { var outString = "Number is " val conn = db.getConnection() try { val stmt = conn.createStatement val rs = stmt.executeQuery("SELECT 9 as testkey ") while (rs.next()) { outString += rs.getString("testkey") } } finally { conn.close() } Ok(outString) } } ``` But of course you need to call close() at some point on the opened connection to return it to the connection pool. Another way is to let Play manage closing the connection for you: もちろん、開いている接続のあるポイントでclose()を呼び出して、接続プールに戻す必要があります。 もう一つの方法は、Playがあなたのために接続を閉じるようにすることです。 ``` scala // access "default" database db.withConnection { conn => // do whatever you need with the connection } ``` The connection will be automatically closed at the end of the block. Tip: Each Statement and ResultSet created with this connection will be closed as well. A variant is to set the connection’s auto-commit to false and to manage a transaction for the block: 接続はブロックの最後で自動的に閉じられます。 ヒント:この接続で作成された各StatementおよびResultSetも閉じられます。 バリアントは、接続の自動コミットをfalseに設定し、ブロックのトランザクションを管理することです。 ``` scala db.withTransaction { conn => // do whatever you need with the connection } ``` For a database other than the default: デフォルト以外のデータベースの場合: ``` scala package scalaguide.sql import javax.inject.Inject import play.api.db.{ Database, NamedDatabase } import play.api.mvc.Controller // inject "orders" database instead of "default" class ScalaInjectNamed @Inject()( @NamedDatabase("orders") db: Database) extends Controller { // do whatever you need with the db } ``` # Selecting and configuring the connection pool 接続プールの選択と構成 Out of the box, Play provides two database connection pool implementations, [HikariCP](https://github.com/brettwooldridge/HikariCP) and [BoneCP](http://www.jolbox.com/). Playは、2つのデータベース接続プール実装、[HikariCP](https://github.com/brettwooldridge/HikariCP)と[BoneCP](http://www.jolbox.com/)を提供します。 The default is HikariCP, but this can be changed by setting the play.db.pool property: デフォルトはHikariCPですが、これはplay.db.poolプロパティを設定することで変更できます: ``` play.db.pool=bonecp ``` The full range of configuration options for connection pools can be found by inspecting the play.db.prototype property in Play’s JDBC reference.conf. 接続プールの設定オプションの全範囲は、PlayのJDBC reference.confのplay.db.prototypeプロパティを調べることで確認できます。 # Testing テスト For information on testing with databases, including how to setup in-memory databases and, see [Testing With Databases](https://www.playframework.com/documentation/2.6.x/ScalaTestingWithDatabases). インメモリデータベースの設定方法を含むデータベースのテストについては、「[データベースでのテスト](https://www.playframework.com/documentation/2.6.x/ScalaTestingWithDatabases)」を参照してください。 # Enabling Play database evolutions Playデータベースのエボリューションを有効にする Read [Evolutions](https://www.playframework.com/documentation/2.6.x/Evolutions) to find out what Play database evolutions are useful for, and follow the setup instructions for using it. [Evolutions](https://www.playframework.com/documentation/2.6.x/Evolutions)を読んで、どのようなPlayデータベースのevolutionsが役に立つのかを調べ、それを使用するための設定手順に従ってください。

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully