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
Related
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
I am having problems connecting to a SQL Server database from C#.
The exception that returns is the login has failed for the specified user, which is clear enough. However, I am not sure why it fails as the username and password are definitely correct. Are there any settings I need to enable on the SQL Server to allow this to happen, as it is a default express install,
Thanks,
Below is my connection code if I'm missing anything obvious.
static void Main(string[] args) {
try
{
SqlConnection con = new SqlConnection(#"Data Source = .\SQLEXPRESS;Initial Catalog=furniture_display;User ID=login;Password=login");
con.Open();
Console.WriteLine("all ok");
con.Close();
}
catch (SqlException err)
{
Console.WriteLine(err);
}
}
According to your code Data Source = .\SQLEXPRESS, you'r trying to connect to a local server. If so you don't need any ID and Password. And be aware of using Catalog, it's somehow tricky and I hate it. To know how it's working, check this out.
Actually I'm using this code and it works like a charm:
SqlConnection con = new SqlConnection(#"Server = localhost; Database = furniture_display; Integrated Security=True;");
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 created a connection and an SqlReader but forgot to close both of them:
SqlConnection conn = new SqlConnection("connection info");
conn.Open();
string sql = "SQL command HERE";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
Now when try to run the code again it always gives me this error:
System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
This link told me how to properly open and close a connection but didn't explain anything on how to close one still running.
I tried shuting down the pc, I tried looking into the database's options on SQL server (found none useful)... I changed the code to do just the close of both the connection and the reader (it compiled and runned but the problem remained after changing back the code).
How can I close this "ghost" connection? Is there any way (brute force) to close all running connections?
[EDIT:] I couldn't really solve the problem. The workaround was to add MultipleActiveResultSets=true to the connection string
I don't think you can access the ghost object, for future, just use using construct where it's possible:
using(SqlConnection conn = new SqlConnection("connection info"))
{
conn.Open();
string sql = "SQL command HERE";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader = cmd.ExecuteReader();
....
}
Wrap the creation in a using statement - this will always ensure the connection gets closed:
using(SqlConnection conn = new SqlConnection("connection info"))
{
// your code
}
Looking at all the answers, they seem to tell you how to avoid the problem.
If I'm not mistaken, what you mean is that a connection exists on both the client (your PC) and the server (The sql server) because you forgot to close it, and you're worried about it hanging out there forever.
Think of your connection to the server as a phone conversation. I could hang up on you, but it takes a few seconds for your phone to realize the connection is lost. You may sit there wondering if I've hung up, or just stopped talking. You really don't know. This is what happens on the server when a connection isn't closed properly. (On older landlines, you could leave the phone off the hook and tied up the line indefinitely.)
By closing the connection in code, you are effectively telling the server to close their end of the connection before closing your own. if you FAIL to close the conneciton, it will be closed on your end when the program exits or if you reboot, but the server may sit there with an open connection. (Think of someone sitting there wondering "Did he just hang up on me?")
If I'm not mistaken, what you want to get to is closing it at the SQL server end. (Getting them to "hang up".)
After rebooting, it is absolutely closed on your end. It should clear on its own at the server.
However, if you want to do it yourself, you can clear it at the server in code end using this info: How do you kill all current connections to a SQL Server 2005 database?
A far easier approach would be to just do it in SQL Server Management Studio as described here: http://www.mikebevers.be/blog/2009/07/kill-open-sql-processes-connections/
All of these answers tell you how to avoid the problem, but they don't explain what the problem is.
A SqlDataReader provides forward-only data access, which means that once you have used it and are done, you must close create a new one. See this blog for a detailed explanation. Basically, if you don't close the DataReader, then underthehood it will remain open dedicated to that connection and command.
As others have stated, its best to ensure you close all your resources.
using (SqlConnection connection = new SqlConnection("...")) {
connection.Open();
string sql = "SQL command HERE";
using (SqlCommand cmd = new SqlCommand(sql, con))
using (SqlDataReader reader = cmd.ExecuteReader()) {
// do your stuff
}
}
Truth be told even when you "close" or "dispose" of a connection it does not really go away unless you explicitly disable Pooling in your connection string. You can however do this
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.clearpool.aspx
I know this is an old post, and this may help no one. But I saw a opportunity to post what I saw wrong with this question.
First, you are creating a SqlConnection named conn but in your SqlCommand named cmd you are calling con as your connection. This is a problem:
SqlConnection conn = new SqlConnection("connection info");
conn.Open();
string sql = "SQL command HERE";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader = cmd.ExecuteReader();
This might be why it's giving you the error:
System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
Second, to close a conn after you are done you use:
conn.Close();
Third, to close a SqlDataReader you use:
reader.Close();
But you just assigned the SqlDataReader to reader. You never actually opened the SqlDataReader. To open it use:
reader.Read();
Or:
while (reader.Read())
{
// Code
}
Now a proper way to initilaize a connection and a SqlDataReader while opening and close them:
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM TableName;";
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
strCol1 = reader.GetValue(0).ToString();
}
reader.Close();
}
conn.Close();
}