I have an MDB file I access using OleDB:
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database.mdb;Persist Security Info=True");
And try to create a new row in a table Users:
connection.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO `users` (`name`, `password`) VALUES ('asd', 'asd')", connection);
cmd.ExecuteNonQuery();
connection.Close();
But nothing happens. I don't get an error message or exceptions, it runs without problems. But when I check the database after the program finished, the table still is empty.
(I already tried the same using DataSets and TableAdapters, but the same happened there: Inserting not committed to database)
That query does not look like an Access query. Have you tried:
"INSERT INTO [users] ([name], [password]) VALUES ('asd', 'asd')"
In Access, table and field names do not use a back-quote, however, reserved words must be enclosed in square brackets.
Related
I'm working in Windows Forms and trying to use OLEDB to connect to an access .accdb file.
I can SELECT data without issue.
I can execute Insert and Create commands with no error.
But when I check the database afterward the data is not showing.
For example, when I create a new Table, the code will say the table was created and if I try to create the table again without closing the Windows Form it will throw an error saying the table already exists, but if I close and restart the program it will let me create the table once more.
Also, if I look into the Access file I wont see the table.
I've tried multiple tests both with Access open and closed. The Connection String is correct as I have made changes to tables in the Access file and they are reflected in the SELECT queries I've sent.
I suspect there must be a setting in Access I must enable for it to autocommit changes. But I haven't found it.
OleDbConnection conn = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =Database2.accdb");
string query = "INSERT INTO [TestTable] ([Test_Name], [Test_Number]) VALUES (?, ?)";
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("Test_Name", list_all_meters[0][0].Name);
cmd.Parameters.AddWithValue("Test_Number", list_all_meters[0][0].Value);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}catch(Exception ex)
{
Debug.WriteLine(ex.Message);
}
Looks like the issue was I had set the Database "Copy to Output Directory" to Copy Always, which overwrote my changes every time I ran the program. Changing it to Copy if Newer fixed the issue.
I am writing a winforms program that gradually inserts into and reads from a MySQL database.
In PHPMyAdmin the fields I insert into are set to utf8_general_ci, and if I insert a row in the MyAdmin interface, it works perfectly. However, if I insert data on-the-fly using my program, certain special characters, like 'Ő' and 'Ű' are saved in the database as 'O' and 'U' respectively.
This is the code I am using:
MySqlConnection conn;
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = sql_string;
conn.Open();
MySqlCommand cmd = new MySqlCommand("", conn);
cmd.CommandText = "INSERT INTO projects (Projects_comment) VALUES (#Projects_comment)";
cmd.Parameters.AddWithValue("#Projects_comment", "ŐŰ");
cmd.ExecuteNonQuery();
conn.Close();
This however, appears as "OU" in the database. I believe the problem is with visual studio's coding. How can I change it, or how to resolve this problem?
I have a remote MySQL database for my company's inventory. The inventory database is the master database for all of the locations we subcontract equipment for. Each property has its own inventory, and for quarterly inventory each location needs to take a laptop and a scanner, and scan their inventory, then sync it to the master database.
The problem is that internet access isn't readily available in all locations, so I need to copy the database to a local file. Concurrency isn't an issue because only one client will ever be connected to the database simultaneously, and each location's database is relatively small, composed of basically <1000 rows of 7 columns.
I have gotten as far as creating an Access file on the HD, but I can't really divine from MSDN how to create a file with a specific schema or how to insert the relevant data from my SELECT statement into said database. I'd been looking onto creating a table adapter on the fly and using .NET's built in methods to do the data transfer, but I still can't find how to create an MS Access file with a specific schema programatically. If anyone has encountered such a problem before, I'd appreciate any insight that could be offered. I basically need to copy the results of a SELECT statement into an MS Access database which I will store locally. All the other code I've got in place.
I'm presently using a rather unwieldy query and foreach loop to do my dirty work, but I was hoping for a more elegant solution, perhaps using a data source created on the fly.
ADOX.Catalog cat = new ADOX.Catalog();
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+ fileName + ";" + "Jet OLEDB:Engine Type=5");
string conString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";" + "User Id=admin;Password=;";
OleDbConnection con = new OleDbConnection(conString);
con.Open();
//create command to generate database schema
OleDbCommand command = new OleDbCommand();
command.CommandText = #"CREATE TABLE items (
[category] VARCHAR(16) NOT NULL,
[manufacturer] VARCHAR(32) NOT NULL,
[model] VARCHAR(32),
[description] TEXT NOT NULL,
[serial_number] VARCHAR(64),
[barcode] VARCHAR(8) NOT NULL PRIMARY KEY,
[property] VARCHAR(4) NOT NULL,
[present] TINYINT
)";
command.Connection = con;
command.ExecuteNonQuery();
OleDbCommand cmdInsert = new OleDbCommand();
cmdInsert.CommandText = "INSERT INTO items([category],[manufacturer],[model],[description],[serial_number],[barcode],[property],[present]) VALUES (#cat,#man,#mod,#desc,#ser,#bar,#prop,#pres)";
cmdInsert.Connection = con;
foreach (DataRow row in itemsTableAdapter1.GetData())
{
cmdInsert.Parameters.AddWithValue("#cat",row.ItemArray[0].ToString());
cmdInsert.Parameters.AddWithValue("#man", row.ItemArray[1].ToString());
cmdInsert.Parameters.AddWithValue("#mod", row.ItemArray[2].ToString());
cmdInsert.Parameters.AddWithValue("#desc", row.ItemArray[3].ToString());
cmdInsert.Parameters.AddWithValue("#ser", row.ItemArray[4].ToString());
cmdInsert.Parameters.AddWithValue("#bar", row.ItemArray[5].ToString());
cmdInsert.Parameters.AddWithValue("#prop", row.ItemArray[6].ToString());
cmdInsert.Parameters.AddWithValue("#pres", row.ItemArray[7]);
cmdInsert.ExecuteNonQuery();
cmdInsert.Parameters.Clear();
}
con.Close();
cat = null;
I tried to do this previously but found that in order to create a new AccessDB I actually had to copy an existing database with all the tables etc that I required.
Would you be able to use sqlite? It is tiny, stable and libraries are available for most languages. You will be able to create whatever structure you like on the client machine.
How do I insert data into a .dbf format database using SQL in Visual c#?
Is it same as when using MS Access?
OleDbConnection dbConn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\wz\Desktop\UBS\onetimecapture\onetimecapture\onetimecapture\bin\Debug\;Extended Properties=dBase IV;");
try
{
// Open connection.
dbConn.Open();
//string queryCutting = "INSERT INTO cuttingstatus.dbf ([Status]) VALUES(adddate)";
string queryCutting = "INSERT INTO cuttingstatus.dbf VALUES(adddate)";
OleDbCommand command_cutting = new OleDbCommand(queryCutting, dbConn);
command_cutting.Parameters.AddWithValue("adddate", "123");
command_cutting.ExecuteNonQuery();
dbConn.Close();
}
catch
{
MessageBox.Show("Error", "SCADA system", MessageBoxButtons.OK);
}
but it return an error say that
The Microsoft Jet database engine could not find the object
'cuttings'.
Make sure the object exists and that you spell its name and the path name correctly.
The database is called cuttingstatus.dbf, and it consist of only a single column Status.
Thanks for the help =)
What is the name of the table in the cuttingstatus.dbf?
The statement should be something like:
INSERT INTO TABLE_NAME
VALUES(adddate)
as the value of the variable queryCutting.
When making an OleDbConnection to use Database files, you want your connection source to point to the logical PATH WHERE the table is... not the actual table.
Connection dbConn = new OleDbConnection(#"Data ource=C:\SomePath\WhereAreAllTables;Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=dBase IV;");
Then, your insert query does not reference the .dbf extension... it is implied by the connection. Also, even though it may be a single column, it would be better to explicitly show the column and values such as :
string queryCutting = "INSERT INTO cuttingstatus ( YourColumnName ) VALUES ( #adddate )";
Next... Is it really a DBase IV system? FoxPro table? Clipper? I would ensure proper provider. If the data is actually from Foxpro origin, I would go to Microsoft and download the Visual Foxpro OleDb provider.
One final thought... is that the error is referring to a truncated table name of up to 8 characters "cuttings" which implies old DOS 8.3 file naming convensions. Don't know if that is what you are also running into for your problem.
when I run this sql:
insert into table1(ID,Name) values ('10','Saeed');
it seems that the record has been inserted, and if I read the table using (select * from table1) it shows me the inserted record, but after closing the program, it disappears.
it's the code:
string constr="Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|" +
"\\Database1.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into st (ID,Name) values ('10','saeed');", con);
cmd.ExecuteNonQuery();
cmd.Close();
I inserted some records in it manually, and when I read the database, the manually inserted records exist.
It is not a transaction problem wont be solved with a transaction!
The issue sounds like you started a transaction and forgot to commit it. However, if you are using the exact code you posted this is not a transaction problem because you are not using one.
That makes me think there is something funky going on with your connection string.
For kicks and giggles trying changing your connection string to something like this
Server=myServerName\theInstanceName;Database=myDataBase;Trusted_Connection=True;
Guess:
You are working with SQL Server Express and "Database1.mdf" within your project is configured (in properties window) for "Copy to Output Directory" value "Always"
Try to specify: "Initial Catalog=InstanceDB;" as well to make sure it does not create a new db name when you restart the application.
error in your code itself
its
con.Close();
not
cmd.Close();
there is no close method for SqlCommand
I agree with pascal. Sounds like the transaction isn't being committed.
(Edited to provide clearer code block from my Comment below)
con.Open();
trans = con.BeginTransaction();
SqlCommand cmd = new SqlCommand( "insert into st (ID,Name) values ('10','saeed');", con);
cmd.ExecuteNonQuery();
tran.Commit();