Java使用jdbc连接MySQL数据库实例分析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java使用jdbc连接MySQL数据库实例分析

  2021-04-03 我要评论

本文实例讲述了Java使用jdbc连接MySQL数据库的方法。分享给大家供大家参考,具体如下:

使用jdbc连接数据库:

可以直接在方法中定义url、user、psd等信息,也可以读取配置文件,但是在web项目中肯定是要使用第二种方式的,为了统一,只介绍第二种方式。

步骤

1、创建配置文件db.properties

无论是eclipse还是myeclipse,在工程下右键->new->file,以properties为后缀名就好了。

配置文件内容:

#连接数据库的url,如果主机地址是localhost,端口是3306也可以写成url=jdbc:mysql:///databasename
url=jdbc:mysql://localhost:3306/databasename
#用户名
user=root
#密码
password=root
#MySQL数据库加载驱动
driverClass=com.mysql.jdbc.Driver

2、定义一个使用jdbc连接数据库的工具类JdbcUtil.java

工具类内容:

public class JdbcUtil{
 //定义全局变量
 private static String url = null;
 private static String user = null;
 private static String password = null;
 private static driverClass = null;
 //读取配置文件内容,放在静态代码块中就行,因为只需要加载一次就可以了
 static{
  try{
   Properties props = new Properties();
   //使用类路径加载的方式读取配置文件
   //读取的文件路径要以“/”开头,因为如果使用“.”的话,当部署到服务器上之后就找不到文件了,使用“/”开头会直接定位到工程的src路径下
   InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");
   //加载配置文件
   props.load(in);
   //读取配置文件信息
   url = props.getProperty("url");
   user = props.getProperty("user");
   password = props.getProperty("password");
   driverClass = props.getProperty("driverClass");
   //注册驱动程序
   Class.forName(driverClass);
  }catch(Exception e){
   e.printStackTrace();
   System.out.println("驱动程序注册失败!!!");
  }
 }
 //获取连接对象Connection
 public static Connection getConnection(){
  try{
   return DriverManager.getConnection(url,user,password);
  }catch(SQLException e){
   e.printStackTrace();
   //跑出运行时异常
   throw new RuntimeException();
  }
 }
 //关闭连接的方法,后打开的先关闭
 public static void close(Connection conn,Statement stmt,ResultSet rs){
  //关闭ResultSet对象
  if(rs != null){
   try{
    //关闭rs,设置rs=null,因为java会优先回收值为null的变量
    rs.close();
    rs = null;
   }catch(SQLException e){
    e.printStackTrace();
    throw new RuntimeException();
   }
  }
  //关闭Statement对象,因为PrepareStatement和CallableStatement都是Statement的子接口,所以这里只需要有关闭Statement对象的方法就可以了
  if(stmt != null){
   try{
    stmt.close();
    stmt = null;
   }catch(SQLException e){
    e.printStackTrace();
    throw new RuntimeException();
   }
  }
  //关闭Connection对象
  if(conn != null){
   try{
    conn.close();
    conn = null;
   }catch(SQLException e){
    e.printStackTrace();
    throw new RuntimeException();
   }
  }
 }
}

可以聊任何java问题,JavaSE、JavaEE

工具类已经实现了,可以直接考到项目里使用,但是有一点要注意,就是这个类文件中没有导入支持的类,大家也可以看到在类的头部没有package import,这个需要自己手动添加上,导入类的快捷键是Ctrl+Shift+O,导包的时候不要导错了;别忘了引入MySQL的支持jar包mysql-connector-java-5.1.7-bin.jar

附:mysql-connector-java-5.1.7-bin.jar可点击此处本站下载

希望本文所述对大家java程序设计有所帮助。

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们