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;"))
Related
I'm trying to connect to a database, but it seems like my connection is not going through. I am using C# MVC for the webpage I'm creating. How can I fix the following error:
System.ArgumentException: 'Keyword not supported: 'metadata'.'.
The error is occuring on the line using (Sqlconnection con = new Sqlconnection(conStr)). What am I doing wrong on this line and is this how you call your SQL query in C# MVC?
string conStr = ConfigurationManager.ConnectionStrings["Training_DatabaseEntities"].ConnectionString;
List<FisYear> YerFis = new List<FisYear>();
using (SqlConnection con = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand("select * from [dbo].[FiscalYear]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
FisYear fy = new FisYear();
fy.FisDate = rdr["ST_FI"].ToString();
YerFis.Add(fy);
}
SelectList list = new SelectList(YerFis, "ST_FI", "FisDate");
ViewBag.DropdownList = list;
}
You're almost certainly trying to use an entity framework connection string to open a connection via new SqlConnection, which won't work.
If you look in your web.config file you'll probably see something similar to:
<connectionStrings>
<add name="Training_DatabaseEntities" connectionString="metadata=res://*/Entity.csdl|res://*.............provider=System.Data.SqlClient;provider connection string=............." />
</connectionStrings>
You could try parsing the connection string by hand to retrieve the bit you actually want, a brief web search suggests that the EntityConnectionStringBuilder may be of use to retrieve it programmatically, here's an example of doing that in a console app:
var connectionString = ConfigurationManager.ConnectionStrings["Training_DatabaseEntities"]
.ConnectionString;
var entityConnectionStringBuilder = new EntityConnectionStringBuilder(connectionString);
var sqlConnectionConnectionString = entityConnectionStringBuilder.ProviderConnectionString;
Console.WriteLine($"EF Connection String: {connectionString}");
Console.WriteLine($"SqlConnection Connection String: {sqlConnectionConnectionString}");
This gives the output (my emphasis):
EF Connection String: metadata=res:///Models.Model1.csdl|res:///Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=cntrra02-sql-rs;initial catalog=Training_Database;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
SqlConnection Connection String: data source=cntrra02-sql-rs;initial catalog=Training_Database;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework
Which shows a connection string that can be passed into a SqlConnection instance.
Keeps throwing the exception:
An unhandled exception of type 'System.InvalidOperationException'
occurred in MySql.Data.dll
here is the code:
Public Sub showWorkerFullnames()
getQuery = "SELECT worker.worker_fullname FROM worker"
getCommand = New MySqlCommand(getQuery, MySQLConnection)
getReader = getCommand.ExecuteReader
cbWorkerFullnames.Items.Clear()
While getReader.Read
cbWorkerFullnames.Items.Add(getReader.Item("worker_fullname").ToString)
End While
This page shows a working example.
Creating a connection:
string connStr =
"server=localhost;user=root;database=world;port=3306;password=******;";
MySqlConnection conn = new MySqlConnection(connStr);
Use that connection object when creating the command:
MySqlCommand cmd = new MySqlCommand(sql, conn);
Open the connection before using it. The linked example opens the connection right after creating it. It's hair-splitting, but I would make opening the connection the very last thing before using it.
conn.Open();
And don't forget to close the connection when you're done.
I have added a SQL Server .mdf database file to my C# application, but when I try to connect with this code, the program causes a connection error.
CODE:
DataSet data;
string con = "Data Source=dbinterno.mdf;";
string queryString = "Select * FROM Dati";
try
{
using (SqlConnection connection = new SqlConnection(con))
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
data = new DataSet();
adapter.Fill(data);
MessageBox.Show(data.ToString());
connection.Close();
}
}
catch
{
MessageBox.Show("\n Problemi di connessione al database");
}
The error is:
ERROR IMAGE
Here are a couple observations:
Your connection string will need to be modified. Try using
string con = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
using Windows Authentication or this:
string con = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;"; using standard security, Source: connectionstrings.com. This should be managed some other way than in code as well. Desktop applications can be de-compiled, and if the password changes, you would need a rebuild. In a ASP.NET application, Microsoft advises to use a web.config file or in the windows registry using a custom subkey.
You will want to use ExecuteReader() for a SELECT statement as ExecuteNonQuery() will not return a result set. See this answer that describes the differences in the types of SQL Server methods
you don't need connection.Close();, the using statement will handle that.
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.
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.