当前位置:   article > 正文

Java mysql(1)----jdbc连接mysql之url书写_mysql jdbc url 只是初次连接的时候使用吗

mysql jdbc url 只是初次连接的时候使用吗

1、参数说明

  1. #autoReconnect 当数据库连接丢失时是否自动连接,取值true/false false
  2. #maxReconnects 如果autoReconnect为true,此参数为重试次数,缺省为33
  3. #initialTimeout 如果autoReconnect为true,此参数为重新连接前等待的秒数 2
  4. #maxRows 设置查询时返回的行数,0表示全部 0
  5. #useUnicode 是否使用unicode输出,true/falsefalse
  6. #characterEncoding 如果useUnicode,该参数制定encoding类型,建议使用utf8
  7. #createDatabaseIfNotExist 当JDBC连接指定数据库,如果此数据库不存在,此参数值为true时,则自动创建此数据库
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2、示例

  1. jdbc:mysql://localhost:3306/hello_mysql?
  2. createDatabaseIfNotExist=true&
  3. amp;useUnicode=true&
  4. amp;characterEncoding=utf8&
  5. amp;autoReconnect=true&
  6. amp;useLocalSessionState=true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3、连接函数

  1. public static Connection getConn(String username,String password,String DBname){
  2. String driver="com.mysql.jdbc.Driver";
  3. String url="jdbc:mysql://localhost:3306/"+DBname;
  4. Connection conn=null;
  5. try {
  6. Class.forName(driver);
  7. conn=DriverManager.getConnection(url,username,password);
  8. } catch (ClassNotFoundException e) {
  9. e.printStackTrace();
  10. } catch (SQLException e) {
  11. e.printStackTrace();
  12. }
  13. return conn;
  14. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

4、测试

  1. public static void main(String[] args) throws SQLException {
  2. Connection conn=getConn("root", "", ""); //没有密码就什么都不写,空字符串
  3. Statement stmt=conn.createStatement();
  4. ResultSet rs=stmt.executeQuery("show databases");//执行查询
  5. while(rs.next()){//遍历查询结果
  6. System.out.println(rs.getString(1));
  7. }
  8. stmt.close();//显示关闭Statement对象,释放资源
  9. conn.close();
  10. //关闭数据库连接,这是个好习惯。尽管在程序运行结束会自动关闭。但web应用是不会结束运行的。
  11. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

—————————————————————————————————————————————————*

java架构师项目实战,高并发集群分布式,大数据高可用视频教程,共760G

下载地址:

https://item.taobao.com/item.htm?id=555888526201
   
   
  • 1
  • 1

01.高级架构师四十二个阶段高 
02.Java高级系统培训架构课程148课时 
03.Java高级互联网架构师课程 
04.Java互联网架构Netty、Nio、Mina等-视频教程 
05.Java高级架构设计2016整理-视频教程 
06.架构师基础、高级片 
07.Java架构师必修linux运维系列课程 
08.Java高级系统培训架构课程116课时 

hadoop系列教程,java设计模式与数据结构, Spring Cloud微服务, SpringBoot入门

—————————————————————————————————————————————————–

版权声明:本文为博主原创文章,未经博主允许不得转载。
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号