Is it necessary to close the connection of sqlite - xamarin

I have read in many tutorial that it is not necessary to close the connection in xamarin sqlite because it is not like the connection in ADO.NET, it is like DbContext in Entityframework but in some tutorials it is said that it is necessary to close the connection
Here is the xamarin code
private readonly SQLiteAsyncConnection _connection;
public ExperiencePage()
{
InitializeComponent();
_connection = DependencyService.Get<ISqLiteDb>().GetConnection();
}
is it necessary to close the connection or not ?

I think is not necessary to close the connection but how it’s a IDisposable object you should Dispose it or use using statement.
using(SqlConnection connection = new SqlConnection("ConnectionString"))
{
// some code here
}

Related

How to handle a connection properly with jooq?

I am getting a lot of inactive sessions in the database which not only take up all the resources but also cause the database to crash occasionally requiring me to restart it.
I am using jooq with kotlin, and this is how I establish a connection.
#Component
class EstDBConnection(private val cfg: DatabaseConfig, private val jooqExecuteListener: PromJooqExecuteListener) {
init {
cfg.migrateFlyway()
}
fun <T> acquire(f: (DSLContext) -> T): T {
return DSL.using(DriverManager.getConnection(cfg.url, cfg.username, cfg.password), SQLDialect.ORACLE10G).use {
jooqExecuteListener.attach(it)
f(it)
}
}
}
You're never closing the connections that you're creating. Please use a connection pool (e.g. HikariCP) to manage your connections. Unless your writing a simple batch script, or some proof of concept, you should never resort to using DriverManager.getConnection directly

Performance monitoring of application

I would like to have special performance log with information about
http request on one line
requested url
elapsed time
username
returned status code
activity id (in case that some request will internally redirected to another action)
I am using serilog now for logging unhandled exceptions. Where is ideal place to add this kind of log insertion or what is best practice ? It is good practice to store logs into the database ?
The middleware approach seems to work.
public class PerformanceMiddleware
{
private readonly RequestDelegate next;
private readonly IConfiguration _configuration;
private readonly ILogger _logger;
public PerformanceMiddleware(RequestDelegate next, IConfiguration configuration, ILogger<PerformanceMiddleware> logger)
{
_configuration = configuration;
_logger = logger;
this.next = next;
}
public async Task Invoke(HttpContext context)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
await next.Invoke(context);
stopwatch.Stop();
try
{
using (var conn = new SqlConnection(_configuration.GetConnectionString("DefaultConnection")))
using (var command = new SqlCommand("dbo.usp_insertPerformance", conn) { CommandType = CommandType.StoredProcedure })
{
conn.Open();
// set parameters
command.ExecuteNonQuery();
}
}
// We dont want show this error to user.
catch (Exception ex)
{
_logger.LogError(ex, "Error in PerformanceMiddleware database operation.");
}
}
}
If you want it simple and use you own solution you could write a Middleware for the asp.net core pipeline to track the required data.
I would not recommend to use Serilog to persist the collected information. Serilog is a logging framework and should not be used to track application metrics.
Use directly a database (sql, mongo, etc.) to store and analyse your data. You have already defined the object model in your question, so it should be easy for you to create and persist an instance of your model in the database.
Why not look at an APM tool or tracing tool to do this versus just creating logs with data that do not allow you to actually identify and solve problems. APm tools provide a lot more value beyond just logging performance data, but instead enable you to solve problems. The leaders in this area are AppDynamics, New Relic, and Dynatrace. There are many open source tools which can help here too, such as Zipkin, Jaeger, and Skywalking. You may want to explain the architecture and language of your app too :)

Java Oracle JDBC Connection Timeout

I have developed some JSON web services using Servlets for my mobile app. I'm using (Oracle + Private Tomcat) hosting. I have one single class DBOperations.java which has a lot of static functions which are called in Servets for database operation. I use getConnection() method in each function to get Connection Object, create statement and execute queries. Issue is after some time connection get lost. I'm using the following code to re-establish the connection.
public static Connection conn;
Statement stmt;
public static Connection getConnection() throws SQLException {
if (conn == null || conn.isClosed() ) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(DB_URL, "username", "password");
return conn;
} catch (ClassNotFoundException | SQLException ex) {
}
} else {
return conn;
}
return conn;
}
I'm unable to figure out how I can handle the timeout/closed connection issue as the above code isn't re-establishing the connection. I need to restart Tomcat to get it back in working state. Any suggestions or help is highly appreciated.
You must use connection pooling, And let Tomcat server to handle everything. Create a JNDI datasource to achieve the same and you will never face such issue.
Used OraceDataSource for connection pooling and it's working perfectly.
public static OracleDataSource ods;
public static Connection getConnection() throws SQLException {
if (ods == null) {
ods = new OracleDataSource();
ods.setURL(DB_URL);
ods.setUser("username");
ods.setPassword("password");
}
return ods.getConnection();
}

Executing native query with Hibernate 4.1

I'm using Hibernate with C3P0 connection pool. In Hibernate 3 I could get access to wrapped C3P0ProxyConnection through BorrowedConnectionProxy and then perform rawConnectionOperation. From what I see BorrowedConnectionProxy is not a part of Hibernate 4.1 anymore.
Is it any way I can run vendor specific queries ? (An instance of proxy connection inside Work.execute does not work for me, I need to execute Oracle stored procedure that takes collection of custom object type).
Thank you .
You can get access to the unproxied Connection in Work by calling:
public void execute(Connection connection) throws SQLException {
Connection unproxiedConnection = connection.unwrap( Connection.class );
...
}
That form leverages the JDBC 4 unwrap method, we simply delegate that to the underlying connection. Or if you specifically need an OracleConnection:
public void execute(Connection connection) throws SQLException {
OracleConnection oracleConnection = connection.unwrap( OracleConnection.class );
...
}
You could also use:
public void execute(Connection connection) throws SQLException {
Connection unproxiedConnection = ( (JdbcWrapper<Connection>) connection ).getWrappedObject();
...
}
I have gone back and forth in terms of contemplating allowing the Work to signify that it wants an unproxied Connection, but given the availability of Connection#unwrap I am not so sure there is an real benefit.

Spring JDBC connection without dataSource

I had read several articles on obtaining Connection using Spring DataSource.
But in our Company Setup, connection object is obtained through already configured environment. Following the sample code:
String pool = PropertyFileReader.getPropertyValue("database.properties", "development.connectionPool");
Connection connection = RequestUtils.getConnection(pool);
Hence, After reading this tutorial
I am confused on using JDBCTemplate using connection object from above code.
I believe JdbcTemplate is not designed to work against a Connection as what you expected. As a workaround, if you are fine to create a separate JdbcTemplate for each connection you created, you may wrap your connection in a thin wrapper of DataSource, and feed it to JdbcTemplate.
I think it should work but I haven't tried it anyway...
class SingleConnectionDataSource implements DataSource {
private Connection connection;
public SingleConnectionDataSource(Connection connection) {
this.connection = connection;
}
public Connection getConnection() {
return this.connection;
}
public Connection getConnection(String username, String password) {
return this.connection;
}
}
// at the place you want to use JdbcTemplate
Connection conn = blablabla; // your own way to get it
JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(conn));
Actually, Spring already provided SingleConnectionDataSource implementation (have seen in version 4.1.7).
It is even allows you to supress connection closing by template.

Resources