1. 程式人生 > >mysql JDBC URL格式各個引數詳解

mysql JDBC URL格式各個引數詳解

mysql JDBC URL格式如下:

jdbc:mysql://[host:port],[host:port].../[database][?引數名1][=引數值1][&引數名2][=引數值2]...

現只列舉幾個重要的引數,如下表所示:

引數名稱 引數說明 預設值 最低版本要求
user 資料庫使用者名稱(用於連線資料庫) 所有版本
password 使用者密碼(用於連線資料庫) 所有版本
useUnicode 是否使用Unicode字符集,如果引數characterEncoding設定為gb2312或gbk,本引數值必須設定為true false 1.1g
characterEncoding 當useUnicode設定為true時,指定字元編碼。比如可設定為gb2312或gbk false 1.1g
autoReconnect 當資料庫連線異常中斷時,是否自動重新連線? false 1.1
autoReconnectForPools 是否使用針對資料庫連線池的重連策略 false 3.1.3
failOverReadOnly 自動重連成功後,連線是否設定為只讀? true 3.0.12
maxReconnects autoReconnect設定為true時,重試連線的次數 3 1.1
initialTimeout autoReconnect設定為true時,兩次重連之間的時間間隔,單位:秒 2 1.1
connectTimeout 和資料庫伺服器建立socket連線時的超時,單位:毫秒。 0表示永不超時,適用於JDK 1.4及更高版本 0 3.0.1
socketTimeout socket操作(讀寫)超時,單位:毫秒。 0表示永不超時 0 3.0.1

對應中文環境,通常mysql連線URL可以設定為:

jdbc:mysql://localhost:3306/test?user=root&password=&useUnicode=true&characterEncoding=gbk&autoReconnect=true&failOverReadOnly=false

在使用資料庫連線池的情況下,最好設定如下兩個引數:

autoReconnect=true&failOverReadOnly=false

需要注意的是,在xml配置檔案中,url中的&符號需要轉義成“&”。比如在tomcat的server.xml中配置資料庫連線池時,mysql jdbc url樣例如下:

jdbc:mysql://localhost:3306/test?user=root&password=&useUnicode=true&characterEncoding=gbk

&autoReconnect=true&failOverReadOnly=false