I am using SQLite in a C#
I have an insert query in a win form that works but on another win form that doesn't. when I have read about the issue it says it might be because there is an open connection somewhere but I have checked it all and even used SQLiteConnection.ClearAllPools(); after every close. now the 1st winform have only 1 open / close, the other one has 3.
I have tried the query using SQLite Browser to make sure it wasn't an issue with the query and it worked successfully. now when I debugged the issue occurs when this line executes cmd.ExecuteNonQuery(); that, of course, executes the query (insert into ....). so I tried changing the type of the table primary key (from varchar to integer). and I still have the issue. below is a sum of how it is.
myconnection = new SQLiteConnection(connectionString);
myconnection.Open();
//select stuff here
//verifications here
//insert inside verification
//finally { myconnection.close(); }
Did you try wrapping your connection in a using statement?
using(var myconnection = new SQLiteConnection(connectionString))
{
myconnection.Open();
//Your code here
}
This will call Dispose method of the connection regardless of execution path, which could possibly be doing more than just closing the connection.
Be aware to click on Write changes on SQLite browser,
if it is running and there are any unsaved changes!
In my case it was very stupid of me, I was making changes in the SQLite browser and did not click on write changes, which locked the DB to be modified by the services. After I clicked the Write changes button, all the post requests worked as expected.
According to #Rohan Shenoy in this topic: SQLite Database Locked exception
may be you should also try this
using (var con = new SQLiteConnection { ConnectionString = "connectionstring" })
{
using(var cmd = new SQLiteCommand { Connection = con })
{
// check state connection if open then close, else close proceed
if(con.State == ConnectionState.Open)
con.Close();
//then
try
{
// try connection to Open
con.Open();
}
catch
{
//catch if found error, message : 'Invalid Connection string'
}
........ // insert query here
} // Close Command
} // Close Connection
Related
Just learning how to create an Windows Forms application via Tom Owsiak C# Windows Forms video tutorials and I'm stuck at the database project (contacts management system) which requires to store data to a database.
I've been following his every single step yet somehow manage to mess up the application writing process. The error happen at the line
SqlConnection conn = new SqlConnection(connString);
Have been searching stackExchange for a while now and try possible solution but still couldn't work it out.
// error occurs here, stated key word not supported, connection timeout
using (SqlConnection connectforfucksake = new SqlConnection(connString))
{
try
{
connectforfucksake.Open(); // open the connection
// create the new SqlCommand object
command = new SqlCommand(insert, connectforfucksake);
command.Parameters.AddWithValue(#"Data_Added", dateTimePicker1.Value.Date);
command.Parameters.AddWithValue(#"Company", txtCompany.Text);
command.Parameters.AddWithValue(#"Website", txtWebsite.Text);
command.Parameters.AddWithValue(#"Title", txtTitle.Text);
command.Parameters.AddWithValue(#"First_Name", txtFName.Text);
command.Parameters.AddWithValue(#"Last_Name", txtLName.Text);
command.Parameters.AddWithValue(#"Address", txtAddress.Text);
command.Parameters.AddWithValue(#"City", txtCity.Text);
command.Parameters.AddWithValue(#"State", txtState.Text);
command.Parameters.AddWithValue(#"Postal_Code", txtPostalCode.Text);
command.Parameters.AddWithValue(#"Mobile", txtMobile.Text);
command.Parameters.AddWithValue(#"Note", txtNote.Text);
command.ExecuteNonQuery(); // pushing whatever in the form into table
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); // show the unforeseen error
}
}
Expected application to take result and then store them into database but it seem like the SqlConnection object instantiate is causing the error.
It sounds like your connection string is simply wrong; most likely, you meant "Connect Timeout" rather than "connection timeout". A basic connection string that includes a connect timeout might be something like:
Data Source=.;Initial Catalog=master;Integrated Security=True;Connect Timeout=42
Hello there I hope you're having a great time.
I have a question And I will break it down into 3 points:
1: create a class to connect to sql server the connection should be made using sql server authentication.
This class should contain several variables for connection parameters.
2: create a user form that shows the current connection parameters. And allow the user to update those parameters. In this form there should be a button to test the connect and another button to save the user changes to the connection parameters.
3: how to share the connection, created by the class we made in point 1, between different forms in the application. Without keeping too many open connections ideally only one connection should be open.
I will add the code that can solve this problem I hope that you can help me refine it.
I am new to all of this.
Thank you all for help.
already exists; SqlConnection and maybe SqlConnectionStringBuilder
that kinda already exists, via the IDE, but last time I checked this was not a redistributable dll. You could, however, simply hook a SqlConnectionStringBuilder to a PropertyGrid - or just write the UI from scratch
even "only one connection should be open" is wrong, IMO - let the inbuilt connection pooling deal with that; all you need is some configuration class with the connection string - and just deal with the connections as you need them, very locally - i.e.
using(var conn = new SqlConnection(Config.ConnectionString))
{
conn.Open();
// NOT SHOWN: do a couple of related operations
} // <== and here, it dies
1 : go to MSDN website you'll find what you need :
http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlcommand.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
2: look at your connection properties (http://msdn.microsoft.com/en-us/library/System.Data.SqlClient.SqlConnection_properties.aspx) and fill a listView or equivalent with it
3: Use previous SqlConnection.Open() to deal with it
Right, I have been tasked with developing a new application in MVC3 that unfortunately has to integrate very slightly with a classic asp web site. This won't be forever as the old site will get an update at some point, but not yet. In the mean time however the new MVC3 application will need a little bit of access to the database for the old site, which is a old MS Access .mdb whereas the new app will be using sql server 2008.
I would greatly appreciate it if someone could give me some examples of how to connect to the access db, aswell as how to execute sql queries (i am fine writing the sql, just got no idea how to execute against the database from my mvc3 app).
thanks in advance
EDIT: I've not got much experience with the old site, but it appears to use the JET adaptor if that helps! ;-)
Your question requires an answer too extensive to be given in detail
I will give you a check list of things and class to research
Define the connection string used to reach your database [see
here]
Create and open the OleDbConnection
Define your OleDbCommand and the command text to be executed
Create and use an OleDbDataReader to read your data line by line
Create and use an OleDbDataAdapter to read your data and load a
DataSet or DataTable
Now don't forget to close your connection and use parametrized query
string connectionString = Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;
public void InsertRow(string connectionString, string insertSQL)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
OleDbCommand command = new OleDbCommand(insertSQL);
// 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 have a problem,
private void button_Submit_Click(object sender, EventArgs e)
{
try
{
string connectionString = #"Data Source=Database_TouchPOS.sdf;Persist Security Info=False;";
using (SqlCeConnection connection = new SqlCeConnection(connectionString))
{
using (SqlCeCommand command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "INSERT INTO Product (Title,Price,Category_Id) VALUES (#title, #price,#category_Id)";
command.Parameters.AddWithValue("#title", textBox_Title.Text);
command.Parameters.AddWithValue("#price", textBox_Price.Text);
command.Parameters.AddWithValue("#category_Id", comboBox_Category.SelectedIndex);
command.ExecuteNonQuery();
MessageBox.Show("Product Added Successfully...");
}
connection.Close();
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Everything seem to be fine, but still can't add data into database.
I did try with complete database path, example c:\project\database.sdf
I did a lot of search before asking. I saw similar problems but not even a single one works for me.
Data are added when compiling but not committed to database. I can see the data after second attempt of debugging.
Please kindly try to explain in detail.
Thanks
You are probably facing this, http://erikej.blogspot.com/2010/05/faq-why-does-my-changes-not-get-saved.html suggest you use a full path to your database file in your connection string.
Did you try to use transactions explicitly?
IDbTransaction transaction = connection.BeginTransaction();
//add to database
transaction.Commit(); // before close connection
This is a very old thread, so I don't know if it will help anyone if I put my answer.
I had this problem, too.
When I executed an update or insert code in C#, apparently, everything was ok, but when I looked up the database, there was no change.
The thing was that while debugging I had the database opened in a Management Studio. And somehow this obstructed the database changes even when there was no error message.
Closing the Management Studio and opening it after executing the code, the changes where perfectly stored in the data base.
Regards.
complete example for those seeking like me... #"Data Source=C:\Users\MYPC\Documents\Visual Studio 2010\Projects\MyProjectFolder\MyProject-1\bin\Debug\MyDatabase.sdf;Persist Security Info=False;";
thank for this example. This saved my day.
I can connect to MySQL database from my WinForms app fine. The question is once I am logged in how can I perform multiple select statements without having to login again?
MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select id from user ";
Then I want to perform a select statement for another table without having to create connection again.
How do I dothis?
I can't seem to just do connection.CreateCommand.
As long as the queries are within the same block, you can use the same connection.. However, once closed, you need to re-open it.
using( YourConnectionObject )
{
... open connection ...
... create your sql querying object... and command
SQLCommand.Connection = YourConnectionObject;
Execute your Query
SQLCommand.CommandText = "a new sql-select statement";
Execute your NEW query while connection still open/active
SQLCommand.CommandText = "a third sql-select statement";
Execute your THIRD query while connection still open/active
... close your connection
}
However, in your application, you can have a single "connection" object like at the application level, or at a form level with the necessary login / connection settings stuff. Then, internally to each form, you can
Open
Run Query
Run Query
Run Query
Close
as needed.
I see you're using a DataReader. You can only have 1 DataReader open at a time per connection. using blocks come in handy for those:
using( var reader = myCommand.ExecuteReader() ) {
while (reader.Read()) {
// get values, do stuff
}
}// reader gets closed
You only hint at it in the code in your question (currently), but it's possible that is part of your problem. You haven't shown how you're using the DataReader, so I'm not certain. Just a possibility.