Can't use MySqlConnection methods outside function - c#

I am new coding and I am trying to create a model DBContext.
I instantiated a connection conn using MySqlConnection. Then I perceived it didn't me allow to use conn methods (like conn.Open()).
I have found a code that uses it inside a function and it seems to work. However I couldn't understand why it has to be inside a function.
Here is my code:
public class DBContext
{
//Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
//start creating connection string
public static string ConnectString
{
get { return "Server=localhost;Database=blog;Uid=root;Pwd=root;"; }
}
public string ConnectionTest()
{
//create an instance of connection
MySqlConnection conn = new MySqlConnection();//Here I can use conn properties/methods
return "";
}
//create an instance of connection
MySqlConnection conn2 = new MySqlConnection();//Here I can't
conn2.open();
}
After reading some documentation about classes and method I understand that classes are references therefore it will not "run".
However I couldn't understand why the error when using conn2.open() is
conn2.open() does not exist in the current context.
shouldn't conn2 exist in the "class context"?

Related

System.InvalidOperationException: 'The ConnectionString property has not been initialized.'

I am trying to fill list boxes with elements and been doing everything by a clean guide but I am getting connection string error when I am trying to run it.
Clearly i have done something foolish and can't understand it so a deeper explanation would be appreciated
The error
The ConnectionString property has not been initialized.
The Code
public partial class FormMain : Form
{
SqlConnection connection;
string connectionString;
public FormMain()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["NaujasAutoSalonas.Properties.Settings.AutoSalonasConnectionString"].ConnectionString;
}
private void FormMain_Load(object sender, EventArgs e)
{
PopulateAutoKlases();
}
private void PopulateAutoKlases()
{
using (connection = new SqlConnection(connectionString));
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM AutoKlases", connection))
{
DataTable KlasesTable = new DataTable();
adapter.Fill(KlasesTable);
lstKlases.DisplayMember = "KlasesPavadinimas";
lstKlases.ValueMember = "KlasesID";
lstKlases.DataSource = KlasesTable;
}
}
}
As you have stated that the connection string property is not initialized,so I guess that your applications is not able to read the connection string from the config file.You can confirm this by putting a breakpoint in the constructor of FormMain class.
If the connection string is not being set in the constructor then you need to identify whether you have declared the connection string properly in your config file.As there could be few config files ,so it is important that you declare your connection string in the correct config file.
Or if you are defining properties for your connection string in the .settings file,you can validate if you are accessing it correctly.

OleDbConnection: How to open and close a connection using a function

I have a function that connects to a Excel File:
public OleDbConnection connection;
public void eConnection(string srcString, string id)
{
conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + srcString + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
connection = new OleDbConnection(conString);
connection.Open();
}
I want to create another function that will close this existing connection when called or invoke
This is what I have to try and close the existing connection:
public void eCloseConnection()
{
connection.Close();
}
How can I close the existing connection using a function that calls the same connection and closes it
How can I test to see if the connection is closed?
Don't do it like this. OleDbConnection implements the IDisposable interface should be disposed as soon as you are done using it, and the best way to do it is to use it as a local variable declared in a using statement:
public void DoStuffWithExcel(string srcString)
{
conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + srcString + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
using(var connection = new OleDbConnection(conString))
{
connection.Open();
// do your stuff here...
}
}
The using statement ensures the connection will be disposed properly even if an exception occurs inside the using block.
This way is the best way to prevent memory leaks, as well as to use the connection pool.
From Microsoft docs page OLE DB, ODBC, and Oracle Connection Pooling:
We recommend that you always close or dispose of a connection when you are finished using it in order to return the connection to the pool. Connections that are not explicitly closed may not get returned to the pool. For example, a connection that has gone out of scope but that has not been explicitly closed will only be returned to the connection pool if the maximum pool size has been reached and the connection is still valid.
Don't keep a global object for a connection hidden inside a class. This adds more problems than the one solved. You should keep track how many time that code is called and how many connection it creates. And of course this makes a lot more complicated the closing part.
Instead the C# language offers a better approach to this kind of problem. An approach particularly suited for objects like a connection that requires unmanaged resources to be realeased to the OS as soon as possible.
You should instead use this approach both if you want to have a class that handles your connections or if you just want to open and use a connection
public static class DbUtility
{
public static OleDbConnection eConnection(string srcString)
{
conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + srcString + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
connection = new OleDbConnection(conString);
connection.Open();
return connection;
}
.... other static utilities
}
Now you can use your class in this way
string srcFile = #"d:\temp\myFile.xlsx";
using(OleDbConnection cn = DbUtility.eConnection(srcFile))
{
.. use your connection
} // <- at this point your connection is automatically closed and disposed.
The using keyword is of great help when you need to just destroy your disposable objects like a connection. In this way you don't keep a global object around when you don't need it.

Connecting to connectionString in app.config

I have my connection string stored in App.Config
<connectionStrings>
<clear />
<add name="CTaC_Information_System.Properties.Settings.CIS_beConn"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source="\\server\file\CIS Data\Database\CIS_be.accdb&quote;;Jet OLEDB:Database Password=123"
providerName="System.Data.OleDb" />
Then when I go to my main.xaml.cs I type in the following:
string cisconn = ConfigurationManager.ConnectionStrings["CTaC_Information_System.Properties.Settings.CIS_beConn"].ConnectionString;`
I found that answer on Stack Overflow when searching, but some were say to put var but when I typed var it wouldn't recognize it so I went with the string method.
When I go to type cisconn.Open(); the option isn't there. I am referencing System.Configuartion;,System.Data.Sql; System.Data.SqlClient; and System.Data.OleDb;.
Can someone show / tell me how I can connect to the database from c#? I'm trying to test the connection when my application runs but I can't figure it out.
The connection string is just a string, its meant to be used in your connection, so you should do:
public void DoSomeDatabaseOp()
{
string cisconn = ConfigurationManager.ConnectionStrings["CTaC_Information_System.Properties.Settings.CIS_beConn"].ConnectionString;
using (OleDbConnection conn = new OleDbConnection(cisconn))
{
conn.Open();
//Create your commands or do your SQL here.
}
}
You should create/destroy the connection inside the method you are using it in. Don't keep a reference to it in the root of the class object. This keeps the connections clean and open if you aren't doing database operations.
If you really wanted to though, you could do this:
class MyClass
{
OleDbConnection _rootConn;
string _connStr;
public MyClass()
{
_connStr = string cisconn = ConfigurationManager.ConnectionStrings["CTaC_Information_System.Properties.Settings.CIS_beConn"].ConnectionString;
_rootConn = new OleDbConnection(_connStr);
}
public void DoSomeDatabaseOp()
{
//Use _rootConn here
}
}
BUT the class should implement IDisposable so that it can dispose of the connection properly! How to implement IDisposable is beyond the scope of the answer, but look up how to implement it properly.

Maintain a single database connection in multiple forms

I have this c# application where the user needs to login through the first form. If validation returns true form2 opens up .
I want to maintain a single connection through all these forms with the same user credentials as entered in form1.I am using ODP.NET to connect to oracle 11g.
Thanks.
Sql connection in .NET is managed by connection pool. So if you instantiate new connection objects, it reuses old closed physical connection.
in form1
using(var c = new SqlConnection("connectionstring"))
{
//use connection here
}
in form2
using(var c = new SqlConnection("connectionstring"))
{
//use connecion here
}
form1 and form2 use same physical connection to database
connection pooling also available for Oracle Data Provider
or maybe you interested in Entity Framework
Create a Static Connectionstring class like
if you declare a Static class with properties of Sqlconnection you can access it in any form or any other class directly here is a sample of class
public static class Connection
{
private static SqlConnection sqlconn;
public static SqlConnection getconnection() {
if (sqlconn==null)
sqlconn = new SqlConnection("Connectionsting.");
return sqlconn;
}
}

The name 'sqlDbType' does not exist in the current context

I'm going to edit textbox value.. but i saw there's a problem
protected void btn_edit_Click(object sender, EventArgs e)
{
DatabaseConnector con = new DatabaseConnector().CreateInstance();
SqlCommand com = new SqlCommand("UPDATE tbl_BinCardManager SET ItemName = #ItemName WHERE ItemNo = #ItemNo");
com.Parameters.Add("#ItemName",sqlDbType.VarChar);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
ERROR 1:
The name 'sqlDbType' does not exist in the current context
ERROR 2:
'ERPSystem.DatabaseConnector' does not contain a definition for 'Open'
and no extension method 'Open' accepting a first argument of type
'ERPSystem.DatabaseConnector' could be found (are you missing a using
directive or an assembly reference?)
My DBConnector Class is :
class DatabaseConnector
{
private DatabaseConnector databaseConnector;
private string connectionString = "Data Source=lernlap;Initial Catalog=ERPSystemDB;User ID=sa;Password=sa123";
public DatabaseConnector()
{
}
private SqlConnection connection;
private bool Connect()
{
try
{
connection = new SqlConnection(connectionString);
connection.Open();
return true;
}
catch(Exception) {
return false;
}
}
internal DatabaseConnector CreateInstance()
{
if (databaseConnector == null)
{
databaseConnector = new DatabaseConnector();
databaseConnector.Connect();
}
return databaseConnector;
}
C# is case sensetive... Try using intellisense.
SqlDbType
The other errors may disappear if you correct the first one.
On a side note, you're going to run into connection/memory leaks without proper resource handling. Personally, I use the using statement to avoid the pitfalls.
I'm not entirely certain what "DatabaseConnector" is, possible your own class, but you should probably be using SqlConnection instead, or possibly SqlDatabase.
Update: I'm not sure if the DBConnector class is supposed to be a singleton or a factory, or both - so I just simplified my answer to avoid using it. Ask another question with detail on how to create the pattern you're looking for and provide the DBConnector class. I think it's do-able, but I just don't have enough info to fix what you have.
public static CONN_STR = "Data Source=lernlap;Initial Catalog=ERPSystemDB;User ID=sa;Password=sa123";
protected void btn_edit_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(CONN_STR))
{
con.Open();
using(SqlCommand cmd = new SqlCommand("UPDATE tbl_BinCardManager SET ItemName = #ItemName WHERE ItemNo = #ItemNo"), con)
{
// TODO: fill in param values with real values
cmd.Parameters.AddWithValue("#ItemName", "my item name");
cmd.Parameters.AddWithValue("#ItemNo", 1);
cmd.ExecuteNonQuery();
}
}
}
SqlDbType the s needs to be capitalized!
yes but theres no any case sensitivity problem know
You actually DO have syntax errors because you used s instead of S. Furthermore
SqlCommand does not have a method called Open() nor does it have one for Close()
You should be using SqlConnection since it contains the methods Open() and Close() and set the SqlCommand's Connection property to your instance of SqlConnection in order to open and close the connection to your database.
You have more errors.
Based on the way you use it, I think you mean SqlConnection instead of DatabaseConnector
You create an SqlCommand named com, but refer to it as cmd
You will need to assign the SqlConnection to the SqlCommand, or it will not know which connection to open.
You only provide 1 parameter to the SqlCommand, while the query needs two (ItemNo as well as ItemName).
Edit, based on your new source:
The error "DatabaseConnector' does not contain a definition for 'Open'" can be corrected by writing con.Connect() instead of con.Open().
However, the other error, that it doesn't have a "Close()" function, can't be corrected - there is no way to tell it to close a connection.
Is this your own code?
Are you using the class made by The Code Project ?
Well, I think the error is because the connection string. The connection string have to be in the class OdbcDatabaseConnector. Well, I never used this class of Code Project, but can be it.
If you are writing with capital 'S' but still get the same error especially in visual studio 2015, then instead of writing 'SqlDbType' , write :
System.Data.SqlDbType
for example:
param[0] = new SqlParameter("#Name", System.Data.SqlDbType.VarChar,50);
Its capital 'S' in SqlDbType, after making the correction, right click on the word, mouse on over to resolve option and add the System.Data namespace. worked for me!

Categories