java 链接数据库时的配置代码
下面的代码是用配置文件连接数据库时的代码:
package com.xinsearch; import java.io.FileInputStream; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class ConnectionTools { static Connection conn=null; static Properties pps=new Properties(); public static Connection getConn() { try { InputStream is=new FileInputStream("properties.properties"); pps.load(is); Class.forName(pps.getProperty("mysqlDriver")); String url=pps.getProperty("url"); String user=pps.getProperty("user"); String password=pps.getProperty("password"); conn=DriverManager.getConnection(url, user, password); return conn; } catch (Exception e) { e.printStackTrace(); } return null; } public static void close() { if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
配置文件需要放在 工程根目录下(名字为properties.properties)格式为:
mysqlDriver:com.mysql.jdbc.Driver url:jdbc:mysql://localhost:3306/1218 user:root password:123