I cannot update an Access 2007 table using C# statements - c#

I'm trying to add records to a MS Access table 2007 using a C# application. My table consists of 3 fields: ID, Name and phone.
For example I tried to add a record for some one with these data: ID=1, Name=Boulis, and phone=1212422. The query didn't return any errors but I didn't find this data in my table.
But the most surprising matter is that when I tried to add the same previous data I got an error saying:
"The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again."
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\boulis.accdb;;Persist Security Info=False ";
con.ConnectionString = ConnStr;
con .Open();
MessageBox.Show("The connection is available now");
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "INSERT INTO info(ID, Name, phone) Values(#StudIDTxt, #StudNameTxt, #StudCNCITxt)";
cmd.Parameters.AddWithValue("#StudIDTxt",1);
cmd.Parameters.AddWithValue("#StudNameTxt", "boulis");
cmd.Parameters.AddWithValue("#StudCNCITxt", 1212422);
cmd.Connection = con;
cmd.ExecuteNonQuery();
MessageBox.Show("table is already updated");
}

The error message you receive on the second attempt clearly indicates that the first attempt was successful. If you already had the table open in Access before performing the INSERT in C# then you won't be able to see the new record until you either
close and re-open the table in Access, or
refresh the Datasheet View (or Form, or whatever). That can be accomplished by clicking the "Refresh All" button in the "Records" section of the "Home" tab (in Access 2010, anyway).

Related

SQL Server duplicate inserts

I have a project (with c# and SQLServer), that it should run on multiple clients and each client should communicate with a central SQL Server. All of the clients and the server are on the same local network.
Everything is ok, but... in some cases, when a insert query runs on a client, multiple duplicate records insert into sql server. This problem occurs rarely.
Below is the query. The query runs when a form is filled and a button click event trigers.
public static int insertSick(string firstname,string lastname,string mobile,string address)
{
using (SqlConnection connection = new SqlConnection(getConnectionString()))
{
string sql = "insert into TSick (Firstname,Lastname,MobileNumber,Address) values
(#fname,#lname,#mobile,#address)";
connection.Open();
SqlTransaction tran = connection.BeginTransaction();
SqlCommand command = new SqlCommand(sql, connection, tran);
command.Parameters.AddWithValue("fname", firstname);
command.Parameters.AddWithValue("lname", lastname);
command.Parameters.AddWithValue("mobile", mobile);
command.Parameters.AddWithValue("address", address);
int nRecord = command.ExecuteNonQuery();
tran.Commit();
return nRecord;
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
// check the text fields and validate them
insertSick(firstname,lastname,mobile,address);
}
The table is as below:
TSick :
- ID --> this column is an incremental identity
- Firstname
- Lastname
- Mobilenumber
- Address
Can someone tell me why in some cases instead of a single record multiple records inserted? How to solve? Do you think that it is a network related problem?
Thanks
It's almost certainly that the user clicks the button twice. You should disable the button as the first thing in your click event handler, and then enable it again at the appropriate time; what constitutes the "appropriate time" is up to you to decide.
Before from the insertion of data in table you can do validation of data whether data is duplicate or not.
First check which column is unique in your table, on the basis of unique column you can check the data otherwise make a composite key(if there is no unique column) in the table and verify the data before from insertion. If a data is duplicate through a message to user.

Invalid object name 'tbl_Shading_Analysis'.?

I am trying to insert textbox value into database in my asp.net project. While using this code some errors are generating. Please help me.
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
con.ConnectionString = (#"connectionString");
con.Open();
cmd.Connection = con;
cmd.CommandText=("INSERT INTO tbl_Shading_Analysis(Load_Band) VALUES ('"+txtLoadBand.Text+"')");
cmd.ExecuteNonQuery();
con.Close();
}
I means the table tbl_Shading_Analysis doesn't exist in the connection you are using, it may cause if you have some triggers attached with the table there may be some issue.
Check if you are connected to the right server/database.
Check any triggers that run on that table as well and make sure all of them have the exact table name spelled correctly.
Try to use the full schema for the referenced table if you have checked above two point for correctness.
Ex: [DatabaseName].[Schema].[TableName] or [Database1].[smmdmm].[aid_data]
That error is coming because the table tbl_Shading_Analysis does not exist in your database.
Check your connection string if you have given the correct database name.
Check if you have created that table in the specified database.
Check if the spelling of the table name is different from what you have specified

Empty database table

I want to insert values in "Navn" row and "Varenr" row in the DB table, when I'm clicking on a button. I have following code:
private void button2_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True"))
{
try
{
SqlCommand cm = new SqlCommand();
cm.Connection = cn;
string col1 = textBox2.Text;
string col2 = textBox3.Text;
//generate sql statement
cm.CommandText = "INSERT INTO ProduktTable (Navn,Varenr) VALUES (#col1,#col2)";
//add some SqlParameters
SqlParameter sp_add_col1 = new SqlParameter();
sp_add_col1.ParameterName = "#col1";
//data type in sqlserver
sp_add_col1.SqlDbType = SqlDbType.NVarChar;
//if your data type is not number,this property must set
//sp_add_col1.Size = 20;
sp_add_col1.Value = textBox2.Text;
//add parameter into collections
cm.Parameters.Add(sp_add_col1);
//in your insert into statement, there are how many parameter, you must write the number of parameter
SqlParameter sp_add_col2 = new SqlParameter();
sp_add_col2.ParameterName = "#col2";
//data type in sqlserver
sp_add_col2.SqlDbType = SqlDbType.NVarChar;
//if your data type is not number,this property must set
//sp_add_col2.Size = 20;
sp_add_col2.Value = textBox2.Text;
//add parameter into collections
cm.Parameters.Add(sp_add_col2);
//open the DB to execute sql
cn.Open();
cm.ExecuteNonQuery();
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
But unfortunately, my data table is still empty:
I have set a breakpoint on the ExecuteNonQuery function, and it is triggered, when pressing on the button:
My table definition:
Your connection string is causing this:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True"
|DataDirectory| Your database that is being updated in this method is in your App Data Directory while the one you are trying to retrieve data from is in your project folder...
|DataDirectory| is a substitution string that indicates the path to the database. DataDirectory also makes it easy to share a project and also to deploy an application. For my PC my App Data Directory is:
C:\Users\MyUserName\AppData\...
If you browse to this location and then go to following folders
...\Local\Apps\2.0\Data
You will be able to find your particular application directory probably stored with your assembly name, or some hash when you go there you will find it the database there is being updated just fine. This connection string is best for deployment.
You can also try this:
If you notice that Server Explorer is detecting all the databases on my PC and you can notice that there are couple of MINDMUSCLE.MDF files but all are at different paths, this is because there is one file in DEBUG directory, one in my PROJECT directory, one in my APP DATA directory. The ones starting with the numbers are stored in my APP DATA directories... If you select your respective database file and then run the SELECT query against it, you will get your data.
I made a tutorial some time ago. May be it will help you:
Check the value that ExecuteNonQuery is returning. It should return an int with the number of records affected by the SQL statement.
If it comes back with a value other than 0, then you know a record is being inserted somewhere. Before you close the connection, run a SQL query against the table to select all of the records and see if they come back through the code.
SELECT * FROM ProduktTable
If you get some records, then you may want to double check the database you're looking at through the IDE and the one your inserting records into through the code. It could be possible that you've got two different databases and you're querying one while inserting into another one.
Those are the steps that I would go through to help narrow down the issue and sounds like something I've probably done before. I hope it helps!

Displaying data from local SQL Server CE database in a gridview C#

I am working on a small application for personal use. It is about keeping some data readily available for me.
It just consists of a local database, functions to add, erase or modify 4 or 5 columns of data and displaying the table in a datagridview.
I have managed to add data to the table and I have managed to use a
SELECT * FROM mytable
statement to get the data and iterate through it but I want to bind the table to the datagridview.
Here is my current method of trying to bind the data:
private void button2_Click(object sender, EventArgs e)
{
string query = "SELECT * FROM myTable";
SqlCeConnection conn = new SqlCeConnection(conString);
using (SqlCeDataAdapter adap = new SqlCeDataAdapter(query, conn))
{
//the adapter will open and close the connection for you.
DataTable dat = new DataTable();
adap.Fill(dat);
dataGridView1.DataSource = dat;
}
}
When I run this code it does not throw an exception and if I change the name of the table to something that does not exists then it causes an exception telling that the table does not exists so I know that it is fetching my table. It simply is not showing it.
Any ideas?
Thanks

Realtime updating MDB database through a datagridview

I am currently trying to create a small program that takes the data from a MDB database that is displayed in a datagridview. The program should allow the user to modify (add, update, delete) the data in the datagridview. Furthermore everything should be updated to the MDB automatically (no buttons). I know there are a lot of topics out there regarding this subject, however for some reason I am unable to reproduce the same results.
I am able to retrieve the data from the MDB file and display it in the datagridview but I am unable to add, modify or delete data. The program keeps throwing exceptions at me but I don't understand why.
First the user has to create a database. The database is generated automatically by code.
private void CreateNewDatabase_Click(object sender, EventArgs e)
{
string DB_FILENAME = "c:\Test.mdb";
// GENERATE THE ACCESS FILES, ITS TABLES AND ITS COLUMNS
var cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0.;Data Source=" + DB_FILENAME; //Use a late bound COM object to create a new catalog. This is so we avoid an interop assembly
var catType = Type.GetTypeFromProgID("ADOX.Catalog");
object o = Activator.CreateInstance(catType);
catType.InvokeMember("Create", System.Reflection.BindingFlags.InvokeMethod, null, o, new object[] { cnnStr });
OleDbConnection cnn = new OleDbConnection(cnnStr);
cnn.Open();
var cmd = cnn.CreateCommand();
// CREATE SCHEDULE TABLE
cmd.CommandText = "CREATE TABLE SCHEDULE ([ID] IDENTITY PRIMARY KEY, [Day] TEXT, [Month] TEXT, [Year] TEXT, [IMS] TEXT, [Customer] TEXT, [Short Description] TEXT, [Long Description] TEXT, [Delivery Ticket Number] TEXT, [Returned] TEXT)";
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO SCHEDULE ([ID]) VALUES (1)";
cmd.ExecuteNonQuery();
// DISPOSE OF THE VARIABLES USED
cnn.Close();
cnn.Dispose();
cmd.Dispose();
}
Once the database has been created it is used in a windows form with a datagridview in it.
public void Initialize()
{
Con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sttngs.DBloc);
Con.Open();
// TRY TO OPEN THE DATABASE FILE AND POPULATE THE DATAGRIDVIEW
da = new OleDbDataAdapter("SELECT [Day], [Month], [Year], [IMS], [Customer], [Short Description], [Long Description], [Delivery Ticket Number], [Returned] FROM SCHEDULE",Con); // WHERE [Returned] = '" + "NO' ", Con);
// POPULATE cBuilder
cBuilder = new OleDbCommandBuilder(da);
ScheduleData = new DataTable();
da.Fill(ScheduleData);
if (ScheduleData.Rows.Count > 0)
{
BindingSource BDS = new BindingSource();
BDS.DataSource = ScheduleData;
this.dataGridView.DataSource = BDS;
}
}
Once the data in the datagridview is changed (handled by the CellValidating event) the data should be updated in the MDB.
private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (ScheduleData.GetChanges() != null)
{
dataGridView.EndEdit();
da.Update(ScheduleData);
ScheduleData.AcceptChanges();
}
}
The code is pretty straight forward but for some reason I am unable to figure out why the data in the MDB is not updated. I have been stuck for a while now so any help would be great!
One thing I can see that will cause an issue is that when you setup your commandbuilder you are not requesting the relevant UPDATE, DELETE & INSERT commands.
When you generate the command builder like this :-
cBuilder = new OleDbCommandBuilder(da);
Follow up with :-
cBuilder.GetUpdateCommand();
cBuilder.GetInsertCommand();
cBuilder.GetDeleteCommand();
You may need to declare all of this in Cell Validating, I'm unsure. Give It a try.
Look this MSDN article over, its for the SQLcommamdbuilder, but the same rules apply :-
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommandbuilder.aspx
Also, You have no open connection to the Data Adapter as you try to update it :-
if (ScheduleData.GetChanges() != null)
{
dataGridView.EndEdit();
//Open a connection Here
da.Update(ScheduleData);
ScheduleData.AcceptChanges();
}
Your SQL String is incorrect, try :-
"SELECT (Day, Month, Year, IMS, Customer, Short Description, Long Description, Delivery Ticket Number, Returned) FROM [SCHEDULE]"

Categories