JDBC開発モード
7311 ワード
一)コードモジュール―――Demo.java
二)ツールモジュール――JdbcUtil.java
三)配置ファイルモジュール―――db.properties
public class Demo {
private static Connection connection;
private static Statement statement;
private static ResultSet rs;
public static void main(String[] args) {
connection = JDBCUtils.getConnection();
try {
statement = connection.createStatement();
rs = statement.executeQuery(SqlMapping.QEURY_ALL);
while (rs.next()) {
System.out.println(rs.getInt("id") + " : "
+ rs.getString("name") + " : " + rs.getString("gender")
+ " : " + rs.getString("salary"));
}
} catch (SQLException e) {
e.printStackTrace();
}
JDBCUtils.closeStream(rs, statement, connection);
}
二)ツールモジュール――JdbcUtil.java
public class JDBCUtils {
private static Properties properties;
//
static {
InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("com/suse/jdbc/db.properties");
properties = new Properties();
try {
properties.load(inputStream);
Class.forName(properties.getProperty("driver"));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//
public static Connection getConnection(){
Connection connection = null;
try {
connection = DriverManager.getConnection(properties.getProperty("url"), properties);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//
public static void closeStream( ResultSet rs, Statement stmt, Connection conn) {
if (null != rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (null != stmt) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
三)配置ファイルモジュール―――db.properties
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://127.0.0.1:3306/mydb
user = root
password = root