Trying to insert a new record into an MS Access .accdb file. When I run the code below, it appears to work fine. No errors are presented, but nothing updates in the database file either. I have verified that the database is in an accessible location.
selectedNote is an object with the three listed parameters. The only field I'm not including in the query string is the ID field which is autonumber.
string scon = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = |DataDirectory|AMS.accdb";
string str = "INSERT INTO Notes ([ItemID], [Note], [Note Date]) VALUES (?, ?, ?)";
try
{
using (OleDbConnection con = new OleDbConnection(scon))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("ItemID", selectedNote.ItemID);
cmd.Parameters.AddWithValue("Note", selectedNote.Note);
cmd.Parameters.AddWithValue("Note Date", selectedNote.NoteDate.ToString("dd-MM-yy"));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
Thanks all, hopefully I can get this hammered out.
EDIT: Curiously, I just found that if I hard-code a path to the .accdb file with a line like the following, it actually does write to that file. So I guess the question becomes why is it not working on the build path where the database is in the same path as the exe.
AppDomain.CurrentDomain.SetData("DataDirectory","C:\temp");
I have tried setting DataDirectory to something like AppDomain.CurrentDomain.BaseDirectory, but this doesn't seem to work either.
A date should not be inserted as text, and you do have the DateTime value, thus:
cmd.Parameters.AddWithValue("Note Date", selectedNote.NoteDate);
Related
I have been attempting to use SQLite database for a Winform C# Project.
The .db file is saved in my project directory and my code has access to it fine. If I enter the value, it works, if I enter the same it errors, as it should.
Once I stop the Windows Form Program and Start it again, all the data I entered is cleared.
Question - How can I ensure the data in the .db file is saved. I guess there's a setting I'm missing.
using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Open();
using (SQLiteTransaction transaction = cnn.BeginTransaction())
{
using (SQLiteCommand cmd = new SQLiteCommand(cnn))
{
SQLiteParameter IDParam = new SQLiteParameter();
SQLiteParameter NameParam = new SQLiteParameter();
cmd.CommandText = "INSERT into Person (ID, Name) VALUES (#ID, #Name)";
cmd.Parameters.AddWithValue("ID", 1);
cmd.Parameters.AddWithValue("Name", "Lewis");
i = cmd.ExecuteNonQuery();
}
transaction.Commit();
//cnn.Execute("insert into Person (ID, Name) values (1, 'Lewis')", person)
}
}
Code for reference.
Resolved
Add the Sqlite database via the tool.
I created a backup on button click
My code for this is
con.Open();
string str = "USE [C:\\Users\\asus\\Documents\\Visual Studio 2012\\Projects\\bbcon_accout_software\\bb_con_accnt_soft_lib\\BbCon.mdf]";
string str1 = "BACKUP DATABASE [C:\\Users\\asus\\Documents\\Visual Studio 2012\\Projects\\bbcon_accout_software\\bb_con_accnt_soft_lib\\BbCon.mdf] TO DISK = 'C:\\Users\\Public\\aa.Bak' WITH FORMAT,MEDIANAME = 'Z_SQLServerBackups',NAME = 'Full Backup of Testdb';";
SqlCommand cmd1 = new SqlCommand(str, con);
SqlCommand cmd2 = new SqlCommand(str1, con);
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
MessageBox.Show("success");
con.Close();
Now I would like to restore the backed up database, please help I searched lots of questions, but I didn't get the answer I need - please help me to perform this task.
I tried to restore using this code:
string query = "RESTORE DATABASE BbCon FROM DISK='C:\\Users\\Public\\aa.Bak' WITH REPLACE";
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.ExecuteNonQuery();
}
con.Close();
but I am getting an error
Please help me with this
Each of the physical files needs to reside somewhere on the system that you're attempting to restore the backed up database to. The error message is telling you that the files are in use by another database. You can query sys.master_files to find out which database they belong to.
To resolve this, you need to either delete the database that is using those physical files or add a MOVE clause into your RESTORE statement. For the latter, it would look something like this:
RESTORE DATABASE BbCon FROM DISK='C:\\Users\\Public\\aa.Bak' WITH REPLACE,
move 'BBCon' to 'c:\temp\BBCon.mdf',
move 'BBCon_log' to 'c:\temp\BBCon_log.ldf';
I'm using Visual Studio 2010 to create a Win Form in c#. It has a handful of Comboboxes, and textboxes that the user can fill out and then submit to an Access DB. My issue comes in when I try to update existing entries. I load an existing entry, make my changes and click update. I do not get any system errors, my connection to the DB is successful, but no changes are actually made to the data. Am I completely missing something? Thanks in advance for any help or insight.
Here is the code for the update button:
private void updateButton_Click_1(object sender, EventArgs e)
{
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\servicereq1.mdb";
OleDbCommand cmd = new OleDbCommand("UPDATE servicereq SET DateLogged = #datelogged, LoggedBy = #loggedby, Function = #function, [Other Impacts] = #summary, Account = #earningsaccount, [From] = #from, [To] = #to, Description = #description, Fixer = #fixer, [Time Estimate] = #timeestimate, [Actual Start] = #actualstart, [Actual Finish] = #actualfinish, [Actual Time] = #actualtime, [Programs/Forms] = #programsforms, Comments = #comments, [Retest Date] = #requestdate, Tester = #tester, Status = #status, [Problem In Environment] = #problemfoundin, [Code In Environment] = #codein WHERE (ServiceRequestNumber = #servreq)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.AddWithValue("#servreq", serviceRequestNumberTextBox.Text);
cmd.Parameters.AddWithValue("#datelogged", dateLoggedTextBox.Text);
cmd.Parameters.AddWithValue("#loggedby", loggedByComboBox.Text);
cmd.Parameters.AddWithValue("#problemfoundin", problem_In_EnvironmentComboBox.Text);
cmd.Parameters.AddWithValue("#function", functionTextBox.Text);
cmd.Parameters.AddWithValue("#summary", other_ImpactsTextBox.Text);
cmd.Parameters.AddWithValue("#earningsaccount", accountTextBox.Text);
cmd.Parameters.AddWithValue("#from", fromTextBox.Text);
cmd.Parameters.AddWithValue("#to", toTextBox.Text);
cmd.Parameters.AddWithValue("#status", statusComboBox.Text);
cmd.Parameters.AddWithValue("#description", descriptionTextBox.Text);
cmd.Parameters.AddWithValue("#fixer", fixerComboBox.Text);
cmd.Parameters.AddWithValue("#codein", code_In_EnvironmentComboBox.Text);
cmd.Parameters.AddWithValue("#programsforms", programs_FormsTextBox.Text);
cmd.Parameters.AddWithValue("#timeestimate", time_EstimateTextBox.Text);
cmd.Parameters.AddWithValue("#actualstart", actual_StartTextBox.Text);
cmd.Parameters.AddWithValue("#actualfinish", actual_FinishTextBox.Text);
cmd.Parameters.AddWithValue("#actualtime", actual_TimeTextBox.Text);
cmd.Parameters.AddWithValue("#requestdate", retest_DateTextBox.Text);
cmd.Parameters.AddWithValue("#tester", testerComboBox.Text);
cmd.Parameters.AddWithValue("#comments", commentsTextBox.Text);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Form Updated Successfully");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
You shouldn't put your database parameters within quotes - they are evaluated as plain text instead of parameters if you do. There is no row where ServiceRequestNumber equals the literal string '#servreq', so nothing is updated.
Also, DataCommands don't pull in local variables as parameters - they must be explicitly added to the DataCommand object (cmd in this case). The reason you aren't getting any errors when you remove your parameter-adding code is because, as stated above, the query doesn't expect any parameters.
Also, the way parameters are being added in the code you removed is strange to say the least. This is much more normal, and significantly easier to read:
cmd.Paramaters.AddWithValue("#paramName", paramData);
//or
cmd.Parameters.Add(new OleDbParameter("#paramName", paramData));
After spending a little more time editing and moving code around, I stumbled on the fact that your parameters must be in the same order in the query as they are when you bind values to them. After making syntactical changes suggested by JoFlash Studios and putting my parameters in the correct order, I was able to make edits to existing data in my form.
I've been trying to add a row to my SQL CE & nothing works I've tried many things I found here at SO or in other websites by googling but to no avail.
Below if the code I have at the moment.
It compiles and executes with no problem, but nothing is added to the table and no exception is thrown.
Could anyone please provide a solution for this ?
string conString = Properties.Settings.Default.TestConnectionString;
using (SqlCeConnection connect = new SqlCeConnection(conString))
{
connect.Open();
string text = "UsernameTest";
string pass = "PasswordTest";
using (SqlCeCommand command = new SqlCeCommand("insert into MyTable values (#Username, #Password)", connect))
{
command.Parameters.AddWithValue("#Username", text);
command.Parameters.AddWithValue("#Password", pass);
command.ExecuteNonQuery();
}
}
Please do not comment about storing a password in plain text, this was just a test.
I'm writing a music player application using WPF (C#). As part of its functionality, I'm populating a music library, where I'm storing the Title and Path to an mp3 file. The user gets to select a root folder for his music library and then the contents are populated in a "Songs" table. This is the code that I've written:
private void Populate_Click(object sender, RoutedEventArgs e)
{
// Folder browser
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.ShowDialog();
string DirectoryPath = System.IO.Path.GetDirectoryName(dlg.SelectedPath);
// Get the data directory
string[] A = Directory.GetFiles(DirectoryPath, "*.mp3", SearchOption.AllDirectories);
string[] fName = new string[A.Count()];
// Initialize connection
string connstr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
// Create the SqlCommand
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "InsertSongs";
// Create the parameters and execute the command
for (int i = 0; i < A.Count(); i++)
{
fName[i] = System.IO.Path.GetFileName(A[i]);
cmd.Parameters.AddWithValue("#Title", fName[i]);
cmd.Parameters.AddWithValue("#Path", A[i]);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Error: " + ex.Message);
}
finally
{
listBox1.Items.Add(A[i]);
listBox2.Items.Add(fName[i]);
cmd.Parameters.Clear();
}
}
// Close the connection
cmd.Dispose();
conn.Close();
conn.Dispose();
}
The code for the stored procedure is simple -
ALTER PROCEDURE dbo.InsertSongs
(
#Title nvarchar(50),
#Path nvarchar(50)
)
AS
INSERT INTO Songs(Title, Path) VALUES(#Title, #Path)
Now, when I execute the program, there is no error message thrown (the file names and directory names have size less than 50). However, at the end of execution, no value is inserted in the Songs table.
The Songs table is described as below:
ID int
Title nvarchar(50)
Path nvarchar(50)
I'm not sure where I went wrong: I have also tried using SqlParameter and then defining the type of parameter as NVARCHAR with size 50, but to no avail. May I kindly request you to assist me here? Many thanks in advance.
The whole User Instance and AttachDbFileName= approach is flawed - at best! Visual Studio will be copying around the .mdf file and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. SongsDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=SongsDatabase;Integrated Security=True
and everything else is exactly the same as before...