当前位置: 移动技术网 > IT编程>开发语言>Java > Java使用jdbc连接MySQL数据库实例分析

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网