我已经编写了一个DB单例类来提供单个数据库连接,我接受另一个类中的连接如果它是null我必须为null检查条件请解释 告诉我最佳做法
class TransferToBigQuery(GoogleCloudStorageToBigQueryOperator):
"""Class to transfer data from Google cloud storage to Big Query"""
def __init__(
self, id, bucket, destination_project_dataset_table, source_objects=None,
schema_fields=None, schema_object=None, source_format='CSV',
create_disposition='CREATE_IF_NEEDED',
skip_leading_rows=0, write_disposition='WRITE_EMPTY',
field_delimiter=',', max_id_key=None, file_xcom=None,
bigquery_conn_id='bigquery_default',
google_cloud_storage_conn_id='google_cloud_storage_default',
delegate_to=None, schema_update_options=(), *args, **kwargs):
super(GoogleCloudStorageToBigQueryOperator, self).__init__(*args,
**kwargs)
另一个班级
public class DBSingleton {
private static final DBSingleton ONLY_ONE = new DBSingleton();
private Connection connection = null;
private DBSingleton() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("url", "username","pwd");// SQLException
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public static DBSingleton getInstance() {
return ONLY_ONE;
}
public Connection getcon() {
return connection;
}
}
答案 0 :(得分:0)
你可以尝试
public class BDConnection {
private static final Logger LOGGER = LoggerFactory.getLogger(BDConnection.class);
private static Connection connection = null;
public static Connection getConnection() {
if(connection == null){
createConnection();
}
return connection;
}
private static void createConnection() {
try {
Class.forName(ImportExportFilesUtils.getResourceMessage("driver.name")).newInstance();
connection = DriverManager.getConnection(ImportExportFilesUtils.getResourceMessage("database.test.url"), ImportExportFilesUtils.getResourceMessage("database.test.username"),
ImportExportFilesUtils.getResourceMessage("database.test.password"));
} catch (Exception ex) {
LOGGER.error("Cannot load the driver for ojdbc", ex);
}
}
public static void closeConnection() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
LOGGER.error("Cannot close the connection with the database", e);
}
}
}
}