标签:except host print word 链接 try res roo stack
这种方式是比较传统的链接方式,比较适合初学者
首先在配置文件中写入你要使用的相关数据
db.properties
driverName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/staff
user = root
password = 123456
然后是一个链接数据库的JDBC工具类,之后你要链接数据库的时候只需要JdbcUtil.getConnection()就可以获取链接
JdbcUtil.java
package com.xinzhi.util; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JdbcUtil { public static Connection getConnection() { Connection connection = null; Properties properties = new Properties(); InputStream inputStream = JdbcUtil.class.getResourceAsStream("/db.properties");//用流的方式读取配置文件 try { properties.load(inputStream); String driverName = properties.getProperty("driverName");//获取配置文件中的相关数据 String url = properties.getProperty("url"); String user = properties.getProperty("user"); String password = properties.getProperty("password"); Class.forName(driverName);//加载驱动器 connection = DriverManager.getConnection(url, user, password);//链接 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return connection; } /**
* 关闭开启的相关事件
**/
public static void close(Statement statement, Connection connection, ResultSet resultSet) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } resultSet = null; } if (statement != null) { try { statement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } statement = null; } if (connection != null) { try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } connection = null; } } }
标签:except host print word 链接 try res roo stack
原文地址:http://www.cnblogs.com/ShaoXin/p/6841304.html