温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-10-24 19:38:01 来源:脚本之家 阅读:174 作者:cat_pp 栏目:编程语言

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Java+MySQL数据库程序设计总结》、《Java数据结构与算法教程》、《Java文件与目录操作技巧汇总》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI