Can't connect to database in vb.net - c#

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.

Related

Exception when trying to open an OracleConnectionObject

I'm trying to open a connection to my university's database that runs on Oracle 11g 11.2.0.1.0 (Oracle.ManagedDaraAccess v18.3.0 is installed on visual studio) with c#.
When I attempt to connect, it throws:
Exception thrown: 'Oracle.ManagedDataAccess.Client.OracleException' in Oracle.ManagedDataAccess.dll"
during the con.open() function at me with no further explanation.
Is there any way to see where the error occurs?
OracleConnection con = new OracleConnection();
OracleConnectionStringBuilder ocsb = new OracleConnectionStringBuilder();
ocsb.Password = pass;
ocsb.UserID = user;
ocsb.DataSource = "<address>:<port>/orcl";
con.ConnectionString = ocsb.ConnectionString;
con.Open();
Add a try catch block around the open() call and resolve the ORA error that shows up in the OracleException

Open database into application c#

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.

cannot open database, on code execution - shows exception

An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.dll but was not handled in user code
Additional information: Cannot open database
"aspnet-mywebsite-20150813211505" requested by the login. The login
failed.
Trying to connect on local .mdf database in visual studio 2013 - web forms.
Created database and c# code for connecting to database. Error shows when i try to execute :
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-mywebsite-20150813211505;Integrated Security=SSPI;"))
{
SqlCommand cmd = new SqlCommand("select * from Users;");
cmd.Connection = con;
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
}
Try this:
#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-mywebsite-20150813211505.mdf;Integrated Security=True"
If this does't work, try to connect to this database using the "Add New Data Source" wizzard and copy the connection string from the auto generated connection string located in the app.config.

The ConnectionString property has not been initialized after "using"

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;"))

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll While writing from textbox to sql server 2012

Trying my first WPF textbox to SQL express connection. I am receiving a An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll While using sql 2012 express trying to write to a table called
EVUSERS
on database
Employee
The error comes at
connection.Open();
Here is my code.
void saveData()
{
try
{
string firstName = FNameTextbox.Text;
string connectionString = #"Data Source=.\\SQLEXPRESS; Database=Employee;Integrated Security=True;User Instance=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = " INSERT INTO EVUSERS (FName) VALUES (#FName)";
command.Parameters.AddWithValue("#FName", firstName);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Here is an image of the table I am trying to insert the data into from the taxtbox. Employee.dbo.EVUSERS
EDIT
Screenshot
I have no idea why there is an error at the open(); Would it be the connections string? or the command I am using? The table definetely exists.
MSDN says
Cannot open a connection without specifying a data source or server. or
The connection is already open.
So check your connection string
using (SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=Employee;Integrated Security=SSPI;"))
{
connection.Open();
SqlCommand command= connection.CreateCommand();
command.CommandText = " INSERT INTO EVUSERS (FName) VALUES (#FName)";
command.Parameters.AddWithValue("#FName", firstName);
command.ExecuteNonQuery();
}
You have two backslashes in the data source in your connection string, but have started the string with # so do not need to escape the backslash.

Categories

Resources