📄 dbconnection.java
字号:
package db;
import java.util.*;
import java.sql.*;
import java.io.*;
public class DbConnection{
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
public DbConnection(){
}
/************************************************
* openConnection
* read file "db.txt"
************************************************/
public boolean openConnection(){
Properties prop = new Properties();
try{
InputStream is = getClass().getResourceAsStream("db.txt");
prop.load(is);
if(is != null) is.close();
}catch(IOException e){
System.out.println("[DbConnection] Open db.txt File, Error!");
}
String jdbc = prop.getProperty("driver");
String uri = prop.getProperty("url");
//System.out.println("jdbc=[" + jdbc + "]");
//System.out.println("uri=[" + uri + "]");
try{
Class.forName(jdbc).newInstance();
}catch(ClassNotFoundException e){
System.out.println("JDBC login, Error!@" + e.getMessage());
return false;
}catch (Exception e){
System.err.println("Unable to load driver!");
e.printStackTrace();
}
try{
this.conn = DriverManager.getConnection (uri);
}catch(SQLException e){
System.out.println("Generate Connection, Error!" + e.getMessage());
return false;
}
return true;
}
/*************************************************
* executeQuery and executeUpdate
* query and update DB
*************************************************/
public ResultSet executeQuery(String query) throws SQLException{
stmt = conn.createStatement();
rset = stmt.executeQuery(query);
return rset;
}
public void executeUpdate(String query) throws SQLException{
stmt = conn.createStatement();
stmt.executeUpdate(query);
if(stmt != null) stmt.close();
}
public void close() throws SQLException{
if(conn != null) conn.close();
if(rset != null) rset.close();
if(stmt != null) stmt.close();
}
protected void finalize() throws Throwable{
close();
}
public static void main(String[] args){
//Design for test purpose.
DbConnection dc = new DbConnection();
System.out.println(dc.openConnection());
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -