达梦数据库连接

时间:2021-09-03 21:52:40

dbconnect.properties文件中定义

DRIVER_NAME=dm.jdbc.driver.DmDriver

DATABASE_URL=jdbc:dm://localhost/YourDbName
DATABASE_USER=SYSDBA

DATABASE_PASSWORD=SYSDBA

使用ResourceBundle获得properties文件中定义

static String configFile = "dbconnect";
public static String getConfigInfomation(String itemIndex) {
try {
ResourceBundle resource = ResourceBundle.getBundle(configFile);
return resource.getString(itemIndex);
} catch (Exception e) {
return "";
}
}

使用Connection获得连接

private Connection connection = null;

public void init(){
try{
       Class.forName(PropertiesConfig.getConfigInformation("DRIVER_NAME"));
       String dbURL = PropertiesConfig.getConfigInformation("DATABASE_URL");
       String username = PropertiesConfig.getConfigInformation("DATABASE_USER")
       String password = PropertiesConfig.getConfigInformation("DATABASE_USER")
       connection = DriverManager.getConnection(dbURL, username, password);
       System.out.println("数据库连接成功!");
   }
   catch(ClassNotFoundException e){
       System.out.println("找不到数据库驱动程序.");
   }
   catch(SQLException e){
       System.out.println("不能打开数据库连接: " + e.getMessage());
   }
}

public void destroy() {
        try{
            connection.close();
        }
        catch(SQLException e){
            System.out.println("不能关闭数据库连接: " + e.getMessage());
        }
    }

创建查询和更新语句

public ResultSet executeQuery(String sql){
Statement statement;
ResultSet resultSet  = null;
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
//statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resultSet;
}

public int executeUpdate(String sql){
Statement statement;
int count  =  0;
try {
statement = connection.createStatement();
count = statement.executeUpdate(sql);
//statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}


public int executeUpdate(String sql,String[] parameter){
PreparedStatement statement;
int count  =  0;
try {
statement = connection.prepareStatement(sql, parameter);
if (parameter != null && parameter.length > 0) {
for (int i=0; i<parameter.length; i++) {
statement.setObject(i+1, parameter[i]);
}
}
count = statement.executeUpdate();
//statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}