javaWeb中mysql数据库连接的两种方式
发布者:IT人在线 | 发表时间:2018/9/12 10:36:28
javaWeb中mysql数据库连接
首先加入mysql 数据库jar包
方法一:直接用数据库连接类
package com.db.cn;
import java.sql.Connection; import java.sql.DriverManager;
public class DB { private static String driver = "com.mysql.jdbc.Driver"; private static String url = "jdbc:mysql://localhost:3306/itrzx"; private static String user = "root"; private static String pwd = "root"; public static Connection getConnection(){ Connection conn=null; try { Class.forName(driver); conn=DriverManager.getConnection(url, user, pwd); } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } return conn; } }
|
方法二:使用反射
1.建立反射文件
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3308/news user=root pass=root
|
2.建立反射类
package com.news.db;
import java.io.IOException; import java.io.InputStream; import java.util.Properties;
public class PropertiesDB { public static String getValue(String key){ Properties prop=new Properties(); InputStream in=new PropertiesDB().getClass().getResourceAsStream("/news.properties"); try { prop.load(in); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return prop.getProperty(key); } }
|
3.建立数据库连接
package com.news.db;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;
public class DB { public Connection getConn()throws Exception{ Class.forName(PropertiesDB.getValue("driver")); Connection conn=DriverManager.getConnection(PropertiesDB.getValue("url"), PropertiesDB.getValue("user"), PropertiesDB.getValue("pass")); return conn; } public void CloseConn(Connection conn){ if(conn!=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { DB db=new DB(); try { db.getConn(); System.out.println("数据库连接成功!"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("连接失败!"); }
} }
|