For some reason, I can't open the Design View of the MS Access table in question; I can look at the data but not the desing, specifically, the length of columns.
When I try to insert a record into said table with this code:
using (var conn = new OleDbConnection(connStr))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText =
#"INSERT INTO tx_header (tx, site_no, xmlfile, collect_dttm, ccr_user, tx_memo, file_beg, file_end)
VALUES(#txval, #siteNum, #xmlfileName, Now(), #ccrUser, #TXMemo, #strfile_beg, #strfile_end)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#txval", tx);
cmd.Parameters.AddWithValue("#siteNum", site_no);
cmd.Parameters.AddWithValue("#xmlfileName", xmlfile);
cmd.Parameters.AddWithValue("#ccrUser", ccr_user);
cmd.Parameters.AddWithValue("#TXMemo", tx_memo);
cmd.Parameters.AddWithValue("#strfile_beg", file_beg);
cmd.Parameters.AddWithValue("#strfile_end", file_end);
conn.Open();
cmd.ExecuteNonQuery();
}
}
...I get, "System.Data.OleDb.OleDbException was unhandled by user code
HResult=-2147217833
Message=The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data.
Source=Microsoft Office Access Database Engine"
Rather than have to guess which column has too much data, it would be nice if I could programmatically determine which column is the problematic one. Can I? How?
There's a pretty detailed explanation of how to query the underlying schema information in MSDN, starting at Retrieving Database Schema Information.
Disclaimer: I've never tried using that against an Access database.
After reading your comments above it looks clear to me that your Access file simply has its designer views locked down. Normally you should be able to unlock them by simply holding Shift, double-clicking the file and keep holding Shift until Access is up and running.
From then on you'll have complete access to tables, queries and the like, and along with it, your database specifications. That will be far better than trying to access that dynamically.
Related
I have a data table, in the data table, I have 3 columns: USERNAME, PASSWORD, and Money.
I want to make a specific setting in my program to make a label the amount of money the user has, and for each user, it will show something else depending on who is logged on at the moment, is it possible and if yes how can I do it?
Thanks in advance.
You can put the amount of money in your label by writing some code. This is used for MSSQL Database connections(in your case).
Here is an example:
using System.Data.SqlClient;//Add this in the using statements at the top of your code.
using (SqlConnection conn = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename =" +Application.StartupPath+ #"\Database1.mdf; Integrated Security = True"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT Money FROM Users WHERE Username = #username";
cmd.Parameters.AddWithValue("#username", "User1");
var reader = cmd.ExecuteReader();
reader.Read();
label1.Text = reader.GetValue(0).ToString(); //reader returns an object, you have to convert it in your type.
//GetValue(selected column number)
}
conn.Close();//This line is optional. The connection closes automatically when the using() statement ends.
}
You can add this code in your Form Load event.(If you are working with Win Forms).
The second method is to use Dataset with binding the label to it. This is also powerful and you do not need to know too much sql or how to code, it is more complicated at the beginning but it`s easier and saves time. You can apply it to any of your form elements(buttons, datagridviews,combobox,textbox,etc).
First, go to your label properties and find "DataBindings". Click on advanced. Just click next until you see the connect to database option. If your are connected already with visual studio to your database it will appear in that combobox, otherwise click new connection(I suppose you worked in service based database).Click next and finish. After you have to bind the label to the database(it will create a generated code in your Form Load Event). If you have only one record(one user) in the table it will show only one value, but if you want to show a specific user, you can change that "Fill" generated method in your Form Load Event in other(filtered one with WHERE SQL Clause). You can change that fill method in the Dataset Added in the bottom of your designer of the form. Click on that little arrow near it and choose "edit in designer" option. Click on the table adapter section and right click on his function(in this case Fill() method) and click configure. Here you can change the sql statement and put a WHERE clause in the end.(ex Where Username = ?) The "?" means some variable. After pass in the function created in the form load event your user`s username next to that dataset thing. Done. If you want to work with Win Forms and sql databases I advise you to learn how to use The Datasets, Bindings and TableAdapters. Hope it helps.
Screenshots of my explanations:
!!!! [UPDATE] !!!!
Here is my example program on google drive: Link.
On the right side you can open my service based database(in the project files(Database1)).I'll attach some useful screenshots for creating addition functions in a dataset's table adaper. Also, you have the second method commented in the Form1 load event.
I want to insert about 2000 records every time a button is clicked.
It works fine until record 511, and throw this exception:
Unspecified Error \r\n Object invalid or no longer set
I've debugged it several times with different records or different order and always get the same error on 511th record.
What's happening?
CODE:
(I read the ID of the last record, before i insert another one)
string CmdText = "SELECT TOP 1 Id FROM MyTable ORDER BY Id DESC";
OleDbCommand com = new OleDbCommand(CmdText,tran.Connection,tran);
com.CommandType = CommandType.Text;
OleDbDataReader reader = com.ExecuteReader(); //exception started here
It sounds like somehow the Jet engine is
not working properly or is corrupted.
When opening and closing connections or recordsets using the Microsoft ODBC Driver for Access or the Microsoft OLE DB Provider for Jet, the following error may be reported:
Object invalid or no longer set.
To resolve this problem, install the latest Microsoft Jet 4.0 service pack 6. For additional information FIX: "Object invalid or no longer set" Error with Microsoft Jet
I've figured it out guys.
I have to close OleDBDataReader every time i want to insert new record.
Now it works fine. Thanks.
The best way to resolve this problem is to delete that table in which its giving error in inserting / updating. and then re-create the table, but be sure, to backup the table data first.
Before I start, I'll let you know that I tried everything that has already been suggested on previous questions and other websites before I considered posting a question myself. As it happens, nothing seems to work and I'm just about fed up with this.
As some background information, this is for my Computing A2 project, so I'm kind of stuck for time now - i.e. I can't be changing loads of my code ideally.
Anyway, onto the issue...
I'm using SQLCe in my code to read from various tables and write to one. So far, the code for reading from the tables works fine, so that's any connection issues out the way first. The piece of code I am struggling with is as follows:
string connectionString = Properties.Settings.Default.BookingSystemDatabaseConnectionString;
using (SqlCeConnection myConnection = new SqlCeConnection(connectionString))
{
myConnection.Open();
try
{
string commandStr = "INSERT INTO bookings(username, room, time) VALUES(#username, #room, #time)";
SqlCeCommand myCommand = new SqlCeCommand(commandStr);
//Passes parameters into SQL command.
myCommand.Parameters.AddWithValue("username", StaticUser.StudentUser.username);
myCommand.Parameters.AddWithValue("room", roomBox.Text);
myCommand.Parameters.AddWithValue("time", timeBox.Text);
//Executes SQL command. Returns the number of affected rows (unecessary for my purposes; a bi-product if you will).
myCommand.ExecuteNonQuery();
}
catch
{
System.Windows.Forms.MessageBox.Show("Could not write new booking to database. This is likely because the database cannot be reached.", "Error");
Program.AccessError = true;
}
myConnection.Close();
}
This is just one of the many ways I have tried to combat the issue I am having. I have also explored:
myCommand.Parameters.Add(new SqlCeParameter("username", StaticUser.StudentUser.username));
to pass the parameters...and another method which escapes me now (using ".Value = StaticUser.StudentUser.username" I think). Furthermore, I have tried using a 'using' statement for the command to save me closing the connection myself (I will probably end up using a solution that uses 'using'). Finally (albeit this isn't a chronological recollection), I tried:
SqlCeCommand myCommand = new SqlCeCommand("INSERT INTO bookings(username, room, time) VALUES(#username, #room, #time)", myConnection)
Again, of course, to no avail.
To highlight the actual symptoms of the issue I am having: The code appears to run fine; stepping through the full method I have pasted above shows that no error is being caught (of course, the message box does not appear - I realised afterwards that stepping through was arguably an unnecessary procedure) and in the other methods I have touched on, the same thing happens. The issue, then, is that the table 'bookings' is not actually being updated.
So, my question, why?
I didn't do the obvious and check the Debug folder for an updated database.
Look for a copy of the database file in your bin/debug folder.
Use full path in connection string, and preferably do not include the sdf file in your project (or at least set build action to None)
i think you are not defining a connection for the command
try
mycommand.connection = connectiostring;
So this is probably the most naive question but that is what questions are for I guess;
Then, my issue is that I have no idea on how to connect Visual C# Express 2010 to Access 2007 and do the typical insert, update, delete, search in an application in C#, I have just learned the basics (finished a console tutorial, which I believe is more than enought, having previous background of VB6 using access 97), and I have been searching here and in the web, but the only thing I could find where the msdn tutorials which I dind't find really clear.
So in my app I just need to link comboboxes, query those values to obtain new ones, do calculations and then store in arrays (and maybe show these in datagrids as well as edit them from said datagrids, which is a bit more complicated I guess) and finally store them in various tables, but I haven't really found a strong (or most likely simple) manual that will guide me to create the typical app insert, update, delete using winforms.
Do you guys have any good links in order to do this?
Thanks.
You can try with this code
Here link about string connection : http://www.connectionstrings.com/access-2007
var query = "...";
var connectionString = "...";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
using(var command = new OleDbCommand(query))
{
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the insert command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
}
I am trying to set up a synchronization routine in C# to send data from a ms access database to a sql server. MS Access is not my choice it's just the way it is.
I am able to query the MS Access database and get OleDbDataReader record set. I could potentially read each individual record and insert it onto SQL Server but it seems so wasteful.
Is there a better way to do this. I know I could do it in MS Access linking to sql server and perform the update easy but this is for end users and I don't want them messing with access.
EDIT:
Just looking at SqlBulkCopy I think that may be the answer if I get my results into DataRow[]
I found a solution in .NET that I am very happy with. It allows me to give the access to the sync routine to any user within my program. It involves the SQLBulkCopy class.
private static void BulkCopyAccessToSQLServer
(CommandType commandType, string sql, string destinationTable)
{
using (DataTable dt = new DataTable())
{
using (OleDbConnection conn = new OleDbConnection(Settings.Default.CurriculumConnectionString))
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
{
cmd.CommandType = commandType;
cmd.Connection.Open();
adapter.SelectCommand.CommandTimeout = 240;
adapter.Fill(dt);
adapter.Dispose();
}
using (SqlConnection conn2 = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))
{
conn2.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(conn2))
{
copy.DestinationTableName = destinationTable;
copy.BatchSize = 1000;
copy.BulkCopyTimeout = 240;
copy.WriteToServer(dt);
copy.NotifyAfter = 1000;
}
}
}
}
Basically this puts the data from MS Access into a DataTable it then uses the second connection conn2 and the SqlBulkCopy class to send the data from this DataTable to the SQL Server. It's probably not the best code but should give anyone reading this the idea.
You should harness the power of SET based queries over RBAR efforts.
Look into a SSIS solution to synchronize the data and then schedule the package to run at regular intervals using SQL Server Agent.
You can call an SSIS package from the command line so you can effectively do it from MS Access or from C#.
Also, the SQL Server, the MS Access DB and the SSIS package do not have to be on the same machine. As long as your calling program can see the SSIS package, and the package can connect to the SQL Server and the MS Access DB, you can transfer data from one place to another.
It sounds like what you are doing is ETL. There are several tools that are built to do this and to me, there is little reason to reinvent the functionality. You have SQL Server, therefore you have SSIS. It has a ton of tools for automated transformations, cleanups, lookups, etc. that you can use out of the box.
Unless this is a real cut-and-dry data load and there is absolutely no scope for the complexity of the upload to increase later on (yeah, right!) I would go with a tried and tested ETL tool.
If SQL Server Integration Services isn't an option, you could write out to a temporary text file the data that you read from Access and then call bcp.exe to load it to the database.
I have done something like this before.
I used
OleDbConnection aConnection = new OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", fileName));
aConnection.Open();
to open the access db. Then
OleDbCommand aCommand = new OleDbCommand(String.Format("select * from {0}", accessTable), aConnection);
OleDbDataReader aReader = aCommand.ExecuteReader();
to execute the read from the table. Then
int fieldCount = aReader.FieldCount;
to get the field count
while (aReader.Read())
to loop the records and
object[] values = new object[fieldCount];
aReader.GetValues(values);
to retrieve the values.
There are several ways to sync but it can give a problem when you change a field name in sql server or add a new column or delete. The best option would be:
Create connections for sql server and oledb.
Write custom query to fetch record from one connection and save it to another.
Before executing make sure to program in a way that you update all table definitions.
In my case this helped in a way because the load on sql server became down.
can you not transfer Access file to the server and delete it once sync is complete?
You can create windows service for that..