Liquibase does not commit my changes - liquibase

I'm running Liquibase from a Java application to MSSQL with the JTDS driver. When I run the updates I see them displayed but nothing actually get's committed to the Database. Any ideas? The code below runs in a Servlet.
Connection con = null;
try {
Properties props = new Properties();
props.load(getClass().getResourceAsStream("/datasource.properties"));
String driver = props.getProperty("database.driver");
String url = props.getProperty("database.url");
String username = props.getProperty("database.username");
String password = props.getProperty("database.password");
Class.forName(driver);
con = DriverManager.getConnection(url, username, password);
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(con));
Liquibase liquibase = new Liquibase("db.xml", new ClassLoaderResourceAccessor(), database);
response.getWriter().print("<PRE>");
liquibase.update("", response.getWriter());
con.commit();
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
log.warn(e.getMessage(), e);
}
}
}
response.flushBuffer();

The update() method that takes a writer will not execute changes, but rather output what would be ran.
If you call liquibase.update("") or liquibase.update(null) instead, it will execute the changes.

Related

Inserting elements into a database table through using ASP.NET

I have been dealing with connecting to a database from an ASP.NET page. After I had filled the associated the registration form I have prepared, when I click the complete registration I am encountering an error:
And here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection baglanti = new SqlConnection("server=BerkPC-IV; Initial Catalog=Okul; Integrated Security=true;"))
{
using (SqlCommand komut = new SqlCommand())
{
komut.Parameters.AddWithValue("#name", TextBox1.Text);
komut.Parameters.AddWithValue("#midname", TextBox2.Text);
komut.Parameters.AddWithValue("#surname", TextBox3.Text);
komut.Parameters.AddWithValue("#phone", TextBox4.Text);
komut.Parameters.AddWithValue("#country", TextBox5.Text);
komut.Parameters.AddWithValue("#city", TextBox6.Text);
komut.Parameters.AddWithValue("#adress", TextBox7.Text);
komut.Parameters.AddWithValue("#passwod", TextBox8.Text);
komut.Parameters.AddWithValue("#email", TextBox9.Text);
try
{
baglanti.Open();
komut.ExecuteNonQuery();
}
catch (SqlException ex)
{
throw;
}
}
}
}
This seems like a db connectivity issue. In your connection string you have not specified the db username and password.
new SqlConnection("server=BerkPC-IV; Initial Catalog=Okul; Integrated Security=true;"))
which mean the exception must be thrown on execution of this line baglanti.Open();

Adding new revision for document in DropBox through android api

I want to add a new revision to the document(Test.doc) in Dropbox using android api. Can anyone share me any sample code or links. I tried
FileInputStream inputStream = null;
try {
DropboxInputStream temp = mDBApi.getFileStream("/Test.doc", null);
String revision = temp.getFileInfo().getMetadata().rev;
Log.d("REVISION : ",revision);
File file = new File("/sdcard0/renamed.doc");
inputStream = new FileInputStream(file);
Entry newEntry = mDBApi.putFile("/Test.doc", inputStream, file.length(), revision, new ProgressListener() {
#Override
public void onProgress(long arg0, long arg1) {
Log.d("","Uploading.. "+arg0+", Total : "+arg1);
}
});
} catch (Exception e) {
System.out.println("Something went wrong: " + e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {}
}
}
New revision is created for first time. When i execute again, another new revision is not getting created.

Sql Notification Supported Isolation Levels for Transactions

I am running multiple inserts using transactions. I am using the SqlDependency class to let the client machine know when the server has been updated.
The problem I am having is that whenever I insert using a transaction, no matter what isolation level I set for the transaction, the SqlNotificationEventArgs returns e.Info as Isolation which indicates that I have the wrong isolation level set for that transactions (I think). When I insert without using a transaction, everything runs smoothly.
My questions is, what are the supported Isolation levels, if any, for transactions when using Sql Notification?
Below is some of the code I am using for the notification:
void DataChanged(object sender, SqlNotificationEventArgs e) {
var i = (ISynchronizeInvoke)_form;
if (i.InvokeRequired) {
var tempDelegate = new OnChangeEventHandler(DataChanged);
object[] args = { sender, e };
i.BeginInvoke(tempDelegate, args);
} else {
var dependency = (SqlDependency)sender;
if (e.Type == SqlNotificationType.Change) {
dependency.OnChange -= DataChanged;
GetData(dependency);
}
}
}
And for the transaction:
public void ExecuteNonQueryData(List<string> commandTexts) {
SqlConnection connection = null;
var command = new SqlCommand();
SqlTransaction transaction = null;
try {
connection = new SqlConnection(GetConnectionString());
connection.Open();
transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
foreach (var commandText in commandTexts) {
try {
command.Connection = connection;
command.CommandText = commandText;
command.Transaction = transaction;
command.ExecuteNonQuery();
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
transaction.Commit();
} catch (Exception ex) {
Console.WriteLine(ex.Message);
} finally {
command.Dispose();
if (transaction != null) transaction.Dispose();
if (connection != null) {
connection.Close();
connection.Dispose();
}
}
commandTexts.Clear();
}
Edit: I was committing the transaction in the wrong place.
Apparently Query Notification does not support transactions. Removing the transaction code fixed this problem.
According to Microsoft:
Transact-SQL does not provide a way to subscribe to notifications. The CLR data access classes hosted within SQL Server do not support query notifications.
This quote was found at http://msdn.microsoft.com/en-us/library/ms188669.aspx, which describes how Query Notifications work and their requirements.

SQL Server, JTDS causes java.sql.SQLException: Invalid state, the ResultSet object is closed

I am using Tomcat 7, Microsoft SQL Server 2008 RC2 and JTDS driver
I am actually using C3P0 as well to try and solve this problem, but it makes no difference at all. I was using Microsoft's driver but it caused me other problems (the requested operation is not supported on forward only result sets)
I get the following error, always at the same point. I have successfully run other queries before getting to this point:
java.sql.SQLException: Invalid state, the ResultSet object is closed.
at
net.sourceforge.jtds.jdbc.JtdsResultSet.checkOpen(JtdsResultSet.java:287)
at
net.sourceforge.jtds.jdbc.JtdsResultSet.findColumn(JtdsResultSet.java:943)
at
net.sourceforge.jtds.jdbc.JtdsResultSet.getInt(JtdsResultSet.java:968)
at
com.mchange.v2.c3p0.impl.NewProxyResultSet.getInt(NewProxyResultSet.java:2573)
at com.tt.web.WebPosition.createPosition(WebPosition.java:863)
The code is as follows:
public static List getListPositions(String query) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
List list = null;
try { //execute the sql query and create the resultSet
con = DBConnection.getInstance().getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()) {
if(rs.isFirst()) {
list = new ArrayList();
}
WebPosition webPos = null;
webPos = new WebPosition(rs);
list.add(webPos);
}
} catch (java.sql.SQLException e) {
System.out.println("SQLException in getListPositions");
System.out.print(query);
Log.getInstance().write(query);
Log.getInstance().write(e.toString());
} catch (Exception ex) {
System.out.print(ex);
ex.printStackTrace();
Log.getInstance().write(ex.toString());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
Log.getInstance().write(e.toString());
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
Log.getInstance().write(e.toString());
}
}
DBConnection.getInstance().returnConnection(con);
}
return list;
}
public WebPosition(ResultSet rs) {
createPosition( rs);
}
public void createPosition(ResultSet rs) {
try {
this.setCurrentDate4Excel(rs.getString("SYSDATE_4_EXCEL"));
this.setExerciseType(rs.getInt("EXERCISE_STYLE_CD"));
...
The code fails in between the above two lines.
I am at a loss to explain why the Result set would be closed in the middle of a function (i.e. it would retrieve rs.getString("SYSDATE_4_EXCEL") but then fail with the error posted at the line rs.getInt("EXERCISE_STYLE_CD"))
Does anyone have any ideas? I imagine that it is some kind of memory issue, and that the connection is automatically closed after a certain amount of data, but I am not sure how to fix this. I tried increasing the heapsize for the JVM.

Managing trace files on Sql Server 2005

I need to manage the trace files for a database on Sql Server 2005 Express Edition. The C2 audit logging is turned on for the database, and the files that it's creating are eating up a lot of space.
Can this be done from within Sql Server, or do I need to write a service to monitor these files and take the appropriate actions?
I found the [master].[sys].[trace] table with the trace file properties. Does anyone know the meaning of the fields in this table?
Here's what I came up with that is working pretty good from a console application:
static void Main(string[] args)
{
try
{
Console.WriteLine("CcmLogManager v1.0");
Console.WriteLine();
// How long should we keep the files around (in months) 12 is the PCI requirement?
var months = Convert.ToInt32(ConfigurationManager.AppSettings.Get("RemoveMonths") ?? "12");
var currentFilePath = GetCurrentAuditFilePath();
Console.WriteLine("Path: {0}", new FileInfo(currentFilePath).DirectoryName);
Console.WriteLine();
Console.WriteLine("------- Removing Files --------------------");
var fileInfo = new FileInfo(currentFilePath);
if (fileInfo.DirectoryName != null)
{
var purgeBefore = DateTime.Now.AddMonths(-months);
var files = Directory.GetFiles(fileInfo.DirectoryName, "audittrace*.trc.zip");
foreach (var file in files)
{
try
{
var fi = new FileInfo(file);
if (PurgeLogFile(fi, purgeBefore))
{
Console.WriteLine("Deleting: {0}", fi.Name);
try
{
fi.Delete();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
Console.WriteLine("------- Files Removed ---------------------");
Console.WriteLine();
Console.WriteLine("------- Compressing Files -----------------");
if (fileInfo.DirectoryName != null)
{
var files = Directory.GetFiles(fileInfo.DirectoryName, "audittrace*.trc");
foreach (var file in files)
{
// Don't attempt to compress the current log file.
if (file.ToLower() == fileInfo.FullName.ToLower())
continue;
var zipFileName = file + ".zip";
var fi = new FileInfo(file);
var zipEntryName = fi.Name;
Console.WriteLine("Zipping: \"{0}\"", fi.Name);
try
{
using (var fileStream = File.Create(zipFileName))
{
var zipFile = new ZipOutputStream(fileStream);
zipFile.SetLevel(9);
var zipEntry = new ZipEntry(zipEntryName);
zipFile.PutNextEntry(zipEntry);
using (var ostream = File.OpenRead(file))
{
int bytesRead;
var obuffer = new byte[2048];
while ((bytesRead = ostream.Read(obuffer, 0, 2048)) > 0)
zipFile.Write(obuffer, 0, bytesRead);
}
zipFile.Finish();
zipFile.Close();
}
fi.Delete();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
Console.WriteLine("------- Files Compressed ------------------");
Console.WriteLine();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine("Press any key...");
Console.ReadKey();
}
public static bool PurgeLogFile(FileInfo fi, DateTime purgeBefore)
{
try
{
var filename = fi.Name;
if (filename.StartsWith("audittrace"))
{
filename = filename.Substring(10, 8);
var year = Convert.ToInt32(filename.Substring(0, 4));
var month = Convert.ToInt32(filename.Substring(4, 2));
var day = Convert.ToInt32(filename.Substring(6, 2));
var logDate = new DateTime(year, month, day);
return logDate.Date <= purgeBefore.Date;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return false;
}
public static string GetCurrentAuditFilePath()
{
const string connStr = "Data Source=.\\SERVER;Persist Security Info=True;User ID=;Password=";
var dt = new DataTable();
var adapter =
new SqlDataAdapter(
"SELECT path FROM [master].[sys].[traces] WHERE path like '%audittrace%'", connStr);
try
{
adapter.Fill(dt);
if (dt.Rows.Count >= 1)
{
if (dt.Rows.Count > 1)
Console.WriteLine("More than one audit trace file defined! Count: {0}", dt.Rows.Count);
var path = dt.Rows[0]["path"].ToString();
return path.StartsWith("\\\\?\\") ? path.Substring(4) : path;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
throw new Exception("No Audit Trace File in sys.traces!");
}
You can also set up SQL Trace to log to a SQL table. Then you can set up a SQL Agent task to auto-truncate records.
sys.traces has a record for every trace started on the server. Since SQL Express does not have Agent and cannot set up jobs, you'll need an external process or service to monitor these. You'll have to roll your own everything (monitoring, archiving, trace retention policy etc). If you have C2 audit in place, I assume you have policies in place that determine the duration audit has to be retained.