I've been tasked with a one time migration from a 4D database to our MSSQL structure. I've got a datasource set up in the ODBC administrator and I was able to connect to it without issues.
I 'reverse engineered' the schema in Visio so I can get a good visual of the relationships between the tables and plan out how I'm going to re-structure the 4D data to fit into our schema. I created a simple console application as this will be a one time run, and I'm able to make the connection to the data source, but as soon as I execute anything, the connection drops or is disabled.
System.Data.Odbc.OdbcConnection conn =
new System.Data.Odbc.OdbcConnection("Dsn=4D v12 datasource");
try
{
conn.Open();
Console.WriteLine("Status of Connection:" + conn.State.ToString());
//Here it says the connection to the DB is open and ready for action
Console.ReadLine();
//pause to visually confirm the connection is open
OdbcCommand com = new OdbcCommand("SELECT * FROM ATable", conn);
com.CommandType = CommandType.Text;
Console.Write(com.ExecuteNonQuery());
//Right here it blows up and closes the connection
}
I also tried to do something with data set and data adapter, but to no avail.
System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection("Dsn=4D v12 datasource");
try
{
conn.Open();
Console.WriteLine("Status of Connection:" + conn.State.ToString());
Console.ReadLine();
OdbcCommand com = new OdbcCommand("SELECT * FROM ATable", conn);
com.CommandType = CommandType.Text;
//Also tried using data sets and data adapters
DataSet dsTest = new DataSet();
OdbcDataAdapter dataAdapter = new OdbcDataAdapter(com);
//but right at this line the connection suddenly disconnects
dataAdapter.Fill(dsTest);
}
catch (Exception e)
{
Console.WriteLine("Failure:" + e.Message.ToString());
// the exception message reads simply connection has been disabled.
Console.WriteLine("Status of Connection: " + conn.State.ToString());
Console.ReadLine();
}
finally
{
Console.Write("Closing connection.");
conn.Close();
Console.Write(".");
conn.Dispose();
Console.WriteLine(".");
Console.WriteLine("Connection Closed and Disposed");
Console.ReadLine();
}
I've tried to look for anyone experiencing this same difficulty, but the documentation I've found has been scarce and not very helpful in this specific regard. There is a good amount of information about executing queries on the 4D product, but not from across the digital divide. Anyone with experience please advise. Thanks for your time and for any help you may be able to give, avid reader.
Apparently the root cause of the issue was in the driver. Upon replacing the driver I got from the website with one sent from the proprietor, the connections ceased being disabled and all is working as intended.
Related
I am getting this issue while trying to read data from an excel file using OleDb.
This is working fine on my test server (Window Server 2008) but not working in UAT server with the same configuration.
It used to work on the UAT server, but suddenly stopped working.
I tried solutions from these sources, but nothing worked:
Intermittent "System resource exceeded" exception for OleDB connection to Microsoft Access data file
OleDbException System Resources Exceeded
System resource exceeded
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter())
{
cmd.Connection = conn;
//Fetch 1st Sheet Name
//conn.Open();
DataTable dtSchema;
dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string ExcelSheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();
//conn.Close();
////Read all data of fetched Sheet to a Data Table
//conn.Open();
cmd.CommandText = "SELECT * From [" + ExcelSheetName + "] Where (F3 = 'Reconstructive' OR F3 = 'Neurovascular' OR F3 = 'Orthobiologics') AND F2 = '"+ SterileProduct.CatalogNumber +"'";
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dt);
}
}
}
Any help would be appreciated.
Thanks
Hope this will be helpful for others.
I went through numerous resource regarding this issue and found many solutions -programmatically and configuration based answers, unfortunately, none of the solutions worked for me and finally, i decided to use CSV file instead excel.
everything is working fine now.
Let me know if anybody found any answer to this question.
Thanks
In a web app, I am using SQL server. However, when I try to store some bulk amount of data, it misses some of the records and does not insert them into the database. I want to know whether there is any commit statement or synchronization for the database? Data is being sent object by object using an ajax call.
Here is my code:
try
{
int surah = Convert.ToInt32(Request["surah"]);
string verse = Request["data"];
string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\PROGRAM FILES (X86)\MICROSOFT SQL SERVER\MSSQL.1\MSSQL\DATA\PEACE_QURAN.MDF;Integrated Security=True";
System.Data.SqlClient.SqlConnection connection = new SqlConnection(connectionString);
string query = "insert into Ayyat_Translation_Language_old_20131209 values(null,null,"+surah+",'"+verse+"')";
SqlCommand cmd = new SqlCommand(query, connection);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
catch(Exception e){
System.IO.StreamWriter file = new System.IO.StreamWriter(#"E:\Office_Work\Peace_Quran\Peace_Quran\Files\ExceptionFile.txt", true);
file.WriteLine("exception details : "+e.ToString());
file.Close();
}
As you understand, the records cannot get lost in the way. Either the INSERT statement would execute, or you would get an exception. Since neither is happening, I believe that you loose something in the request generating mechanism.
I would strongly suggest to put some logging message on each request. You will probably find out that your requests are less than you thought. This could be for a number of reasons, but since I don't know the exact mechanism calling the server side code, I cannot have an opinion.
Hope I helped!
I am trying to get column information in C# from a SQL table on SQL Server. I am following the example in this link: http://support.microsoft.com/kb/310107 My program strangely gets hung up when it tries to close the connection. If the connection is not closed, the program exits without any Exceptions. Here's my code:
SqlConnection connection = new SqlConnection(#"MyConnectionString");
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast.
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
connection.Close(); // Alternatively If this line is commented out, the program runs fast.
Putting the SqlConnection inside a using block also causes the application to hang unless CommandBehavior.KeyInfo is changed to CommandBehavior.SchemaOnly.
using (SqlConnection connection = new SqlConnection(#"MyConnectionString"))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast even here in the using
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
}
The table in question has over 3 million rows, but since I am only obtaining the Schema information, I would think this wouldn't be an issue. My question is: Why does my application get stuck while trying to close a connection?
SOLUTION: Maybe this isn't optimal, but it does work; I inserted a command.Cancel(); statement right before Close is called on connection:
SqlConnection connection = new SqlConnection(#"MyConnectionString");
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast.
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
command.Cancel(); // <-- This is it.
connection.Close(); // Alternatively If this line is commented out, the program runs fast.
I saw something like this, long ago. For me, it was because I did something like:
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader();
// here, I started looping, reading one record at a time
// and after reading, say, 100 records, I'd break out of the loop
connection.Close(); // this would hang
The problem is that the command appears to want to complete. That is, go through the entire result set. And my result set had millions of records. It would finish ... eventually.
I solved the problem by adding a call to command.Cancel() before calling connection.Close().
See http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=610 for more information.
It looks right to me overall and I think you need a little optimization. In addition to the above suggestion regarding avoiding DataReader, I will recommend to use connection pooling. You can get the details from here :
http://www.techrepublic.com/article/take-advantage-of-adonet-connection-pooling/6107854
Could you try this?
DataTable dt = new DataTable();
using(SqlConnection conn = new SqlConnection("yourConnectionString"))
{
SqlCommand cmd = new SqlCommand("SET FMTONLY ON; " + yourQueryString + "; SET FMTONLY OFF;",conn);
conn.Open();
dt.Load(cmd.ExecuteReader());
}
SET FMTONLY ON/OFF from MSDN seems the way to go
There is an specific way to do this, using SMO (SQL Server management objects)
You can get the collection of tables in the database, and then read the properties of the table you're interested in (columns, keys, and all imaginable properties)
This is what SSMS uses to get and set properties of all database objects.
Look at this references:
Database.Tables Property
Table class
This is a full example of how to get table properties:
Retrieving SQL Server 2005 Database Info Using SMO: Database Info, Table Info
This will allow you to get all the possible information from the database in a very easy way. there are plenty of samples in VB.NET and C#.
I would try something like this. This ensures all items are cleaned up - and avoids using DataReader. You don't need this unless you have unusually large amounts of data that would cause memory issues.
public void DoWork(string connectionstring)
{
DataTable dt = new DataTable("MyData");
using (var connection = new SqlConnection(connectionstring))
{
connection.Open();
string commandtext = "SELECT * FROM MyTable";
using(var adapter = new SqlDataAdapter(commandtext, connection))
{
adapter.Fill(dt);
}
connection.Close();
}
Console.WriteLine(dt.Rows.Count);
}
I have a problem with a customer. I have this code:
var conn = new SqlConnection(Util.GetConnectionString());
var DataCommand = new SqlCommand();
var sql = "";
// subseccion
try
{
sql = "TRUNCATE TABLE preview_" + tablename;
DataCommand = new SqlCommand(sql, conn);
DataCommand.Connection.Open();
int numcol = DataCommand.ExecuteNonQuery();
sql = "insert into preview_" + tablename+ " select * from " + tablename;
DataCommand = new SqlCommand(sql, conn);
DataCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
var latest_error = ex.Message;
Util.Add_Event_Log(latest_error);
}
finally
{
DataCommand.Dispose();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Dispose();
}
This do the next thing, I give a name of a table, it TRUNCATE a table then copy the information from "table" to "preview_table" and it works as expected.
However, we found that if we don't give TRUNCATE permission for the table, it fail. But, my problem is that it does not only fail but also deleting the current session (and may be also restart the server process).
My bet it is a server problem (server 2003) may be it is not patched or anything because I am working inside a try-catch part so it should not fail in this fashion.
My customers says the problem is in the code.
But I am not sure, maybe I should not a sql command in a chain.
Is this happening in the development environment as well as production environment? If so, you need to step through your code with the VS debugger and pin point the line at which the session is being deleted.
You should also check the event logs on the production server to see if they can provide any information.
As stated in the comments by msergey, it may be the Util.Add_Event_Log throwing an exception but you should test this by stepping through the code.
If it is Util.Add_Event_Log causing the issue, move this code out of the catch into its own try/catch statement by declaring an exception variable in the outer scope.
If it does wind up that the use of TRUNCATE is the culprit you might try swapping that out in favor of using a DELETE statement instead. Performance won't be as great, but you wouldn't require elevated user permissions in SQL Server either.
Im using the code below, to update a record in an MS Access database, to store some information related to a property grid, however, im receiving a syntax error when the query tries to execute, and i cannot figure out why. ConnCheck simply looks to see if the connection is open, and if not, it opens it.
Thanks in advance
Main_Class.ConnCheck();
OleDbCommand cmd = new OleDbCommand("UPDATE [CALCULATION_RUN_TBL] SET [CAP_INPUTS]=?, [RA_INPUTS]=?, WHERE [CALCULATION_RUN_ID]=?", Main_Class.con);
try
{
cmd.Parameters.Add("#CAP_INPUTS", OleDbType.LongVarBinary).Value = SaveCAPSettings();
cmd.Parameters.Add("#RA_INPUTS", OleDbType.LongVarBinary).Value = eig.SaveSettings();
cmd.Parameters.Add("#CALCULATION_RUN_ID", OleDbType.Integer).Value = Main_Class.Calculation_Run_ID;
//Main_Class.con.Open();
cmd.ExecuteNonQuery();
Main_Class.con.Close();
}
catch (OleDbException ex)
{
//get the error message if connection failed
MessageBox.Show("Error in connection ..." + ex.Message);
Main_Class.con.Close();
}
Well a quick look says you have an extra comma
This: [RA_INPUTS]=?, WHERE should be [RA_INPUTS]=? WHERE