This is my code:
conn = new SqlConnection("Server=(localdb)\\v11.0;Integrated Security=true;AttachDbFileName=|DataDirectory|\\Users.mdf;MultipleActiveResultSets=True;");
conn.Open();
SqlCommand comm = new SqlCommand("update users set surname='simpson' where id=1", conn);
int i = comm.ExecuteNonQuery();
MessageBox.Show(i + "");
comm = new SqlCommand("select surname from users where id=1", conn);
SqlDataReader reader = comm.ExecuteReader();
if (reader.Read())
MessageBox.Show(reader[0] + "");
conn.Close();
The ExecuteNonQuery returns 1 to show the database has been updated and the second query confirms it. But when I open the database in visual studio 2013, there are no changes, database still the same
YOu mean, when you stop the program and Visual Studio throws away the copy of the database and resets it to the empty one then the data is gone? Yes, that is true.
Maybe you need to change your connectionstring, or refresh the database.
Apparently the database had been set to copy to the output folder each time
Related
I am building an application for a group of friends and myself to use for DnD sessions. Part of the program involves taking all of the values that are entered for our characters, items, etc and storing them to a database. I have the database built, and am pulling from the database into the program, however I am unable to return data to the database. I have the data coming into a dataset, and all of my edits are affecting the dataset, but I cannot get anything to affect the actual source database tables.
Below I have the button that I intend to use to update items in the characters' packs. I have both dataadapter, and tableadapter methods included that I have tried.
private void btnaddpack_Click(object sender, EventArgs e)
{
if (txtbxpack.Text != "")
{
/*connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE Pack SET Item = (#ItemName)" + "WHERE Id = '" + this.lstpack.SelectedValue + "';";
cmd.ExecuteNonQuery();
cmd.Clone();*/
string packitem = txtbxpack.Text; //will take item from an textbox
this.packTableAdapter.Insert(packitem);
this.Validate();
this.packBindingSource.EndEdit();
this.packTableAdapter.Update(this.dnD_MachineDataSet.Pack);
}
PopulatePack();
Here is my populate code in case someone needs that:
private void PopulatePack()
{
using (connection = new SqlConnection(connectionString)) //this is all about opening the connection to the sqldatabase, normally it would need to be closed, but this uses idisposable, so it will close itself
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Pack", connection))
{
DataTable packtable = new DataTable();
adapter.Fill(packtable);
lstpack.DataSource = packtable;
lstpack.DisplayMember = "Item";
lstpack.ValueMember = "Id";
}
}
As mentioned above, all of the changes are appearing whenever I re-populate the listboxes that draw upon the dataset, hence why this is an issue of trying to get that data back into the source database. I will make the obligatory "I'm relatively new to using databases" statement as it will do no good to pretend that I am an expert.
Thanks.
In the commented code, you would need to do the following:
assign the connection object to the SqlCommand object's Connection
property
pass the item name to your #ItemName parameter
assign a parameter value to the 'Id' column in the WHERE clause
remove, 'cmd.Clone();', and replace with, 'connection.Close();'
Here is what the code should look like:
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "UPDATE Pack SET Item = (#ItemName) WHERE Id = #ID;";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ItemName", txtbxpack.Text);
cmd.Parameters.AddWithValue("#ID", this.lstpack.SelectedValue);
cmd.ExecuteNonQuery();
connection.Close();
I'm trying to retrieve data from database and display it in a listbox. I've got the following code and when I run it, it gives no error or something but no data is showing up in the listbox.
connection.Open();
DataTable dt = new DataTable();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from Appointments where PersonID = '" + textBox4.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
dt.Load(reader);
foreach (DataRow Dr in dt.Rows)
{
listBox1.Items.Add(Dr["PersonID"].ToString());
}
connection.Close();
You don't show your connection string, but it sounds like one of the old gotchas when working with file based databases (Access as it seems you're using) from within Visual Studio.
If your MDB file is part of the project, and its "Action" is set to "Copy always", then every time you run your application, the MDB file in the BIN folder will get overwritten by the one in your source folder, thus overwriting any changes you made in the last run.
Please verify that this is not the case as it's one common source of problem.
Cheers
In Visual Studio (2013) I have added service-based database (Database1.mdf) in my project. I have added in it a table, and via Show Data Table added two rows. Reading data from database works as required. But there is a problem with add value to database. If I while the program is running add value to database and then press "Reading data" it's ok, the data is reading. But If I while the program is still running go to "Show Data Table" and press button "update", I get the error: "This database cannot be imported. It is either an unsupported SQL Server verison or an unsopported database compatibility".
If I press button "update" in "SQL Server Object Explorer" and then go to "Show Data Table" and press button "update", the data is updates, but no added data. Also, after the completion of the program there isn't the added data.
Why?
I have tried to change the properties "Copy To Output Directory" from "Copy always" to "Do not Copy" or "Copy if newer". But it didn't help me. Please help me
Read data:
string strConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnectionString))
{
try
{
SqlCommand command = new SqlCommand("SELECT [Login] FROM [UsersTable];", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
label1.Text = "Last value: " + reader.GetString(0);
}
}
}
catch (SqlException ex)
{
}
Add data:
string strConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(strConnectionString))
{
using (SqlCommand command2 = new SqlCommand())
{
command2.Connection = con2;
command2.CommandType = CommandType.Text;
command2.CommandText = "INSERT INTO [UsersTable] ([Login], [Password]) VALUES (#Login, #Password)";
command2.Parameters.AddWithValue("#Login", textLogin.Text);
command2.Parameters.AddWithValue("#Password", textPassword.Text);
try
{
con2.Open();
command2.ExecuteNonQuery();
}
catch (SqlException)
{
// error here
}
finally
{
con2.Close();
}
}
}
Update
Perhaps the example isn't clear enough for you.
private void SubmitNote(string message)
{
// Ensure parameter isn't null.
if(string.IsNullOrEmpty(message))
return;
// Our Insert Query:
string insert = #"INSERT INTO [Notes] ([Username], [Date], [Message])
VALUES (#Username, #Date, #Message);";
// Define our Connection & Command:
using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
using(SqlCommand command = new SqlCommand(insert, connection))
{
// Open Connection
connection.Open();
// Define our Command (AddWithValue / Add Approach)
command.Parameters.Add("#Username", SqlDbType.VarChar, 50).Values = User.Identity.Name;
command.Parameters.AddWithValue("#Date", DateTime.Now);
command.Parameters.Add("#Message", SqlDbType.VarChar).Value = message;
// Execute Query:
command.ExecuteNonQuery();
}
}
So anytime I'd like to insert a message to the database I simply call:
SubmitNote("What is love, baby don't hurt me.");
That would execute without any issues, assuming the parameter and connection are valid. You could write an exception helper, but that is above and beyond your issue. One of the problems your potentially having is:
Parameter may be Null
An issue within your Command Text
Potential issue with your Connection String.
Based on the issue you mentioned, a value is Null which means it doesn't contain a valid value. For instance if you do:
String message = String.Empty;
SubmitNote(message);
That would fail, as message doesn't have a value. Hopefully this helps.
I am trying implement a SQL INSERT command into my MS Access database using C# with Visual Studio 2012.
But after that, when I open my Access database, there is no updates even the insert command can be successfully created by showing the success pop-up window after executeNonQuery()
Would you please tell me how to make this insert into SQL command work?
This is my code
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = #"INSERT INTO STUDENT(CHI_NAME, ENG_NAME, NICK_NAME,
BD_YYYY, BD_MM, BD_DD,
HOME_TEL, NO_OF_CHILD, PARENT_EMAIL,
SEC_EMAIL, STUDENT_ADDR, DISTRICT,
MOTHER_NAME, MOTHER_TEL, MOTHER_OCCU,
FATHER_NAME, FATHER_TEL, FATHER_OCCU,
E_NAME, E_TEL, E_RELATIONSHIP, REMARKS)
VALUES(#NEW_CHI_NAME, #NEW_EN G_NAME, #NEW_NICK_NAME,
#NEW_BD_YYYY, #NEW_BD_MM .....);"
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#NEW_CHI_NAME", chi_name);
cmd.Parameters.AddWithValue("#NEW_ENG_NAME", eng_name);
cmd.Parameters.AddWithValue("#NEW_NICK_NAME", nick_name);
cmd.Parameters.AddWithValue("#NEW_BD_YYYY", bd_year);
cmd.Parameters.AddWithValue("#NEW_BD_MM", bd_month);
....
cmd.Connection = connection;
connection.Open();
cmd.Transaction = connection.BeginTransaction();
int rows= cmd.ExecuteNonQuery();
if(rows > 0)
{
MessageBox.Show("Insert New Client Success!");
}
else
{
MessageBox.Show("Insert New Client Failed!");
}
cmd.Transaction.Commit();
connection.Dispose();
connection.Close();
In Solution Explorer, right click your Access file, choose Properties, and set Copy To Output Directory to Copy if Newer
Go to the debug directory, you will find you accdb file copied there. Open it and verify.
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);
}