基本的なJDBC接続データベース
3573 ワード
以前使っていたjavaでデータベースに接続する方法を最近整理します.まず、PropertiesファイルリンクSQL Serverデータベースを採用します.
データベース接続クラス:DBUtil.java
リソースファイル:jdbc.properties
jdbc.propertiesはプロジェクトsrcの下に配置され、構成に成功しました.
データベース接続クラス:DBUtil.java
package com.jdbc.jdbcConnection;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* Properties
*
* version 1.0
* @author zjc
* @since 1.0
*/
public class DBUtil {
private final static Properties props = new Properties();
static {
InputStream input = DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
try {
props.load(input);
Class.forName(props.getProperty("driverClass"));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
String url = props.getProperty("url");
String user = props.getProperty("user");
String password = props.getProperty("password");
Connection conn = null;
Statement stmt = null;
PreparedStatement pst = null;
ResultSet rs = null;
public Connection getConnection() {
try {
conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public Statement getStatement() {
getConnection();
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return stmt;
}
public PreparedStatement getPreparedStatement(String sql) {
getConnection();
try {
pst = conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return pst;
}
public ResultSet getReslutSet(String sql) {
getStatement();
try {
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public boolean update(String sql){
getStatement();
boolean flag = false;
try {
stmt.execute(sql);
flag = true;
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
public void close() {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
リソースファイル:jdbc.properties
driverClass=net.sourceforge.jtds.jdbc.Driver
url=jdbc:jtds:sqlserver://127.0.0.1:1433/db
user=username
password=password
jdbc.propertiesはプロジェクトsrcの下に配置され、構成に成功しました.