There is no error in this code but when i insert the values,they are not actually inserted in database.
Here is my connection string class :
public class DBConn
{
public static SqlConnection GetConnection()
{
string sDBPath = Application.StartupPath + #"\App_Data\Database3.mdf";
string connStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename='" + sDBPath + "';Integrated Security=True;User Instance=True";
return new SqlConnection(connStr);
}
}
and in this class i call the connection string class :
string query = "INSERT INTO Table1 VALUES('" + textBox1.Text + "')";
SqlConnection con = DBConn.GetConnection();
SqlCommand com = new SqlCommand(query,con);
con.Open();
using (con)
{
com.ExecuteNonQuery();
MessageBox.Show("Insert");
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Do work here; connection closed on following line.
}
Your use of the using statement is not recommended and leads to
problems. You have to instantiate the resource object inside the
using statement! It's scope or lifetime is now limited to the
statement block and will be properly garbage collected. The way you
use it (by passing an already instantiated object into the using
statement) the objects remains valid although not properly accessible
since it was never properly closed or disposed. MSDN - using
statement. So instead of creating the connection and passing it
around your application (bad practice) you should create the
connection settings (connection string) and the query and use
them to create a connection resource inside a using statement
everytime you need a connection. This way the resource is
always correctly disposed. The provided link gives you an
example how to use a using statement.
Check your connection string well if all provided information is
valid or all needed information is provided (e.g. username and password).
Check database settings (e.g. permissions)
SqlConnection class has an event called InfoMessage. In case the
connection produces any warnings or errors you will get notified.
Check your database (e.g. log) for the occurance of errors.
Related
I'm new to C#. This is, in fact my first project in this particular language.
In the following code:
namespace FuelBurnImport {
class DataWriter {
private string qs = "SELECT * FROM fuel_burn_data_meta;";
public DataWriter(BurnDataHeader bdh, BurnDataFlight bdf) {
SqlConnection cn = OpenCN();
// work in progress. more to be added here...
}
private SqlConnection OpenCN() {
private string cs = #"Data Source=server; APP=FuelBurnImporter; Initial Catalog=database; Integrated Security=true";
return new SqlConnection(cs).Open();
}
}
}
I get intellisense errors in the OpenCN() private method
the OpenCN() method declaration says Not all code paths return a
value
the { following the OpenCN() { method declaration says expected
"}"
the end of line private string cs also says expected "}"
the cs in new SqlConnection(cs) says does not exist in current
context
new SqlConnection(cs).Open() error says "a namespace cannot directly contain members..."
However, if I remove private from in front of private string cs, all these errors go away and it appears to be happy.
Am I misusing the private method in some way? Am I misusing the private string declaration? I have a feeling that even if I remove the private from in front of the string field declaration, it's still going to break.
The string declaration within a method is local, so it makes no sense to make it private. Thus, you are committing a syntax error (and, in my view, a semantic error) by using the private keyword in there. The variable cn cannot possibly leak as it's inaccessible from other methods, and different instances of the same method on the same object have different "cs" things (I'm not sure but you can create a private static const string outside the method and use it in the method, if you really want to see "private" in the declaration of the variable).
Fix this first.
Before the actual return occurs, the "using" statement will automatically close the connection and you'd return a closed connection. This may or may not cause a syntax error, but if it does, I'd say it should be more explicit.
Make cn a private member of the class;
Do not use using {} or dispose cn in an other way in OpenCN;
Implement IDisposable on your class.
https://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.110).aspx
Don't put using in OpenCN. using ensures that the variable created is disposed. If you do that you'll be returning a SqlConnection which has already been closed.
Instead, change OpenCN to this:
private SqlConnection OpenCN()
{
var cs = #"Data Source=server; APP=FuelBurnImporter; Initial Catalog=database; Integrated Security=true";
var cn = new SqlConnection(cs);
cn.Open();
return cn;
}
Also, don't call OpenCN from the constructor. That's going to create an opened connection when you create an instance of DataWriter. Don't create and open a connection until you need it. That way you can create it, open it, use it, and then dispose it (which also closes it) as soon as possible.
Whatever the method is that's going to actually execute some SQL, create the connection there. If you call OpenCN from there, then you would do
using(var connection - OpenCN())
{
//execute your SQL using the connection
}
Regarding your error, just remove the private keyword from the connection string declaration:
private string cs = #"Data Source=server; APP=FuelBurnImporter; Initial Catalog=database; Integrated Security=true";
However, you will have some problems because your connection will be closed as soon as using stament completes. Also it's not recommended to open your connections for long time. Simply make the using statement and open the connection just at the moment when you need to execute the query.
After using block "}" - return null because using block only return the value not the function
No need declare private string inside function
Better way function implementation
private SqlConnection OpenCN()
{
string cs = #"Data Source=server; APP=FuelBurnImporter; Initial Catalog=database; Integrated Security=true"; SqlConnection cn = new SqlConnection(cs);
cn.Open();
return cn;
}
My connection string, my database, and everything is working just fine, but just when I call it once at my page.
I have several methods that make connection to my database and return a value to me, and for the first time i need to use two of then. And i'm getting this error in conn.Open():
"The ConnectionString property has not been initialized."
"Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code."
Exception Details: System.InvalidOperationException: The ConnectionString property has not been initialized.
When i call just one is working great.
My source of two of this methods is, i'm using almost the same code for everyone, just changing the table name:
public DataTable Category(){
sda = new SqlDataAdapter("select * from tbl_category", conn);
sda.Fill(dt);
return dt;
}
and
public int CategoryLastId(){
using (conn){
conn.Open();
sqlCommand = new SqlCommand("SELECT MAX(Id) AS LastID FROM tbl_category", conn);
sqlCommand.ExecuteNonQuery();
Int32 newId = (Int32)sqlCommand.ExecuteScalar();
conn.Close();
return Convert.ToInt32(newId);
}
}
feels like they are in conflict(also, calling on .Get with NHibernate, but this also is working fine)
The problem is that the using statement is closing the connection when it returns.
Create the SqlConnection inside your using statement as follows:
using (SqlConnection conn = new SqlConnection(connString)) { ... }
For getting the connection string from your config file:
connString = ConfigurationManager.ConnectionStrings["yourConnString"].ConnectionString;
The configuration file:
<connectionStrings>
<add name="yourConnString" connectionString="..." providerName="..."/>
</connectionStrings>
Change using statement like below. Refer this for more connection strings.
using (SqlConnection conn = new SqlConnection("Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"))
I am trying to make a simple MS Access Database connection by using the SqlConnection and SqlCommand objects.
As you can see here is how I make the connection:
private SqlConnection GetConnection()
{
String connStr = ConfigurationManager.ConnectionStrings[0].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
return conn;
}
And before you ask, yes I have tried to move this piece of code to the method that calls it. Didn't change anything. It still reads the connection string wrong.
The connection string looks like this and is located in the App.config file:
<add name="ConnString" connectionString="Server=*.*.*.*;Database=familie;User Id=mfs;Password=********;"/>
But when I get this error:
And look at the connection string object at the time, the string looks like this:
"data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
I have spent about 2 hours now trying to make this work, going to many different sites to figure out what I did wrong, but I either get information is that is too old, conflicting or deals with connecting to a local database, when this is in fact an external one access through a proxy that was given to me by my client (TrustGate if anyone should ask)
The method that calls GetConnection() looks like this:
public Dictionary<int,String> GetPostNrList()
{
SqlConnection conn = GetConnection();
SqlCommand cmd = new SqlCommand("Execute dbo.HENT_POST_NR_LISTE", conn);
var reader = cmd.ExecuteReader();
Dictionary<int, String> liste = new Dictionary<int, string>();
while (reader.NextResult())
{
int post_nr = (int) reader.GetSqlInt32(0);
String by = reader.GetString(1);
liste.Add(post_nr, by);
}
CloseConnection(conn);
return liste;
}
What exactly am I doing wrong?
The exception message tells you exactly what the problem is - your connection is not open. You just need to open the connection prior to executing a command:
conn.Open();
BTW, a good pattern is to using a using block when dealing with SQL connections, to ensure it gets disposed properly:
using (var conn = GetConnection())
{
using (var comm = xxxxxxx)
{
conn.Open();
using (var rdr = comm.ExecuteReader())
{
// xxxxx
}
}
}
You don't have to specifically close anything - the using pattern does all that for you.
I would like to apply my connection string to the whole winform. If I do this in this case - it will apply to the whole win form, but then i cannot use textbox to enter details:
public partial class Form1 : Form
{
SqlConnection myConnection = new SqlConnection("user id=userName;" +
"password=userPass;" +
"server=.;" +
"Trusted_Connection=yes;" +
"database=dbName; " +
"MultipleActiveResultSets=True;" +
"connection timeout=30");
public Form1()
{
InitializeComponent();
}
And if I will use with textbox I will need to enter the connection string to each method.
Is there anyway to get around it?
Another approach you can take is create the SqlConnection when it is needed and then store in a private variable if you want to save the reference.
So when you need the connection have:
if( myConnection == null )
{
string connectionString = string.Format( "user id={0}, password={1}", userIdTextBox.Text, passwordTextBox.Text );
myConnection = new SqlConnection( connectionString );
}
You will extend the "string.Format" to include the other connection properties.
If you require the "myConnection" in multiple places then place the above code into a method named "GetConnection", have it return an SqlConnection instance using the contents of the textboxes and call this method each time a connection is required.
EDIT:
Personally I would have a method that builds the connection string, like described above, and create a new SqlConnection instance whenever it is needed. This will attempt to open a new connection each time, but will make use of connection pooling built into the ADO.NET library.
using( SqlConnection connection = new SqlConnection( this.GetConnectionString() ) )
{
// Open Connection
// Access the database
// Close the connection <- Manual closing MAY not be needed as it might be done in Dispose ...check MSDN for clarification.
}
You can create a static class to store the connection string in there. It is not a good practice to create always the connection string.
I have an application that fires a mysql command (query) "show databases", the query works and returns properly but I can't close my connections. The user I used had 24 connections allowed at the same time so the problem popped up further down my program but reducing the allowed connections to 2 shows me that I can't even close the first query (which isn't in a loop). The code is the following:
protected override Dictionary<string, Jerow_class_generator.Database> loadDatabases()
{
MySqlConnection sqlCon = new MySqlConnection(this.ConnectionString);
sqlCon.Open();
MySqlCommand sqlCom = new MySqlCommand();
sqlCom.Connection = sqlCon;
sqlCom.CommandType = CommandType.Text;
sqlCom.CommandText = "show databases;";
MySqlDataReader sqlDR;
sqlDR = sqlCom.ExecuteReader();
Dictionary<string, Jerow_class_generator.Database> databases = new Dictionary<string, Jerow_class_generator.Database>();
string[] systemDatabases = new string[] { "information_schema", "mysql" };
while (sqlDR.Read())
{
string dbName = sqlDR.GetString(0);
if (!systemDatabases.Contains(dbName))
{
databases.Add(sqlDR.GetString(0), new MySQL.Database(dbName, this));
}
}
sqlCom.Dispose();
sqlDR.Close();
sqlCon.Close();
sqlCon.Dispose();
return databases;
}
P.S. The 'New MySQL.Database(dbName, this));' is my owm made class which only stores the DB structure, could be considered irrelevant.
The exact error I get is 'max_user_connections'. on the connection.open line of the next time a query needs to be fired.
Rather than keeping track of all the Open/Close/Dispose calls all over the place, I'd recommend just replacing all of those with using statements. This will make sure the expected scope of each object is clear and that it will be destroyed/disposed upon exiting that scope.
Close() nor using will help alone with your problem because ADO.NET is using its own connection pooling and connections are by default not closed until program is closed. There are few options to solve this, but consider performance implications and is this really desired behavior for your application.
Add ";Pooling=False" to your connection string.
SqlConnection.ClearPool Method
SqlConnection.ClearAllPools Method
For more information read: SQL Server Connection Pooling (ADO.NET)
Along with the using suggestions above, when creating your sqlDR variable you should use the CloseConnection command behavior to close the actual connection if that is your intended action. As noted in the documentation here.
When the command is executed, the associated Connection object is closed when the associated DataReader object is closed.
So your code to instantiate your reader would look like this:
//to instantiate your variable
MySqlDataReader sqlDR;
sqlDR = sqlCom.ExecuteReader(CommandBehavior.CloseConnection);
//closing your datareader reference here will close the connection as well
sqlDR.Close();
If you wrap all your code in a using block using the above method, you don't need any of those Close() or Dispose() methods other than the sqlDR.Close();
when use "using" key word what happen is.when the garbage collector activate it first dispose objects which was declred in using statement.
I recommend using connection pooling in combination with the MySqlHelper class, passing the connection string as the first argument. That allows MySQL to open the connection if necessary, or keep it open according to the pooling cfg, without you having to know about it.
I changed my code to use 1 connection and keep it open and when testing I came across an error that a datareader should be closed. Now since all my queries didn't close the dataReader object (I used dataTable.Load(cmd.ExecuteReader()).) I think the problem might be there.
Keeping 1 open connection worked perfectly so I don't know what caused the not closing problem. I gues it was the dataReader not closing by itself.
Close() will definitely help you close your.
using (MySqlConnection conn = GetConnection())
{
conn.Open();
using (MySqlCommand cmd = conn.CreateCommand())
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "UserDetail";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new Album()
{
Id = Convert.ToInt32(reader["UId"]),
Name = reader["FirstName"].ToString(),
ArtistName = reader["LastName"].ToString()
});
}
}
}
}
In the above code, you can see one if condition before opening the connection it will help you to reuse your already open connections check below code.
if (conn.State != ConnectionState.Open)
{
conn.Open();
}