I have this method:
static void DbConnect()
{
// Connects to the Db using a simplified Connection string.
try
{
mySqlConnect = new MySqlConnection("server=" + Setup_Controller.server + ";uid=root;");
mySqlConnect.Open();
}
// If a password is required, tries again using the password provided.
catch (MySqlException)
{
mySqlConnect = new MySqlConnection("server=" + Setup_Controller.server + ";uid=root;password='" + Setup_Controller.password + "';");
mySqlConnect.Open();
}
}
However every time it catches an exception, it won't load open the connection because of the current exception caused by the first connection attempt. I am beginning to wonder whether it's because the try/catch is not allowing the program to continue, because there is an unhandled exception in play?
If you really want to use this method, you need to first close your connection before you can use it again.
static void DbConnect()
{
// Connects to the Db using a simplified Connection string.
try
{
mySqlConnect = new MySqlConnection("server=" + Setup_Controller.server +
";uid=root;");
mySqlConnect.Open();
}
// If a password is required, tries again using the password provided.
catch (MySqlException)
{
//make sure connection is close
if(mySqlConnection != null)
mySqlConnect.Close();
}
/* i don't know what this class looks like but most data class expose some method
to see if the connection is still open or close. If there is not an IsOpen check
for IsClose or something like this
*/
if(!mySqlConnect.IsOpen())
{
try
{
mySqlConnect = new MySqlConnection("server=" + Setup_Controller.server +
";uid=root;password='" + Setup_Controller.password + "';");
mySqlConnect.Open();
}
catch (MySqlException)
{
//make sure connection is close
mySqlConnect.Close();
}
}
Related
I got two problems:
First, i'm trying to connect my windows form app with my embedded database (.dbf) and i keep getting this message no matter what i do to the connection string:
"error isam instalable cant be found"
Second, i would like to make the path relative to the executable.
Thanks, here is the code i'm using to test the whole thing:
private void bGuardar_Click(object sender, EventArgs e)
{
try
{
string cadena = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source =D:\\; Extended Properties = dBASE IV; UserID =; Password =;";
OleDbConnection con = new OleDbConnection();
con.ConnectionString = cadena;
con.Open();
MessageBox.Show("conected");
con.Close();
}
catch (OleDbException exp)
{
MessageBox.Show("Error: " + exp.Message);
}
}
For the second part, you can get the path of your executable using System.IO.Path.GetDirectory(Application.ExecutablePath). There are more ways do this based upon your need (see Best way to get application folder path).
To avoid further difficulties instead of
'OleDbConnection con = new OleDbConnection();'
try
using (OleDbConnection con = new OleDbConnection())
{
; // your command and executes here
}
this way you call the dispose / close method always (using generally wraps up your code so that the part between { and } is wrapped in a try / catch block with finally that calls a dispose() / close() on the OleDbConn object.
I'm trying to create an installer file that installs a database using install shield 2015.
I'm following this link
Walkthrough: Using a Custom Action to Create a Database at Installation
Since this link refers to an older install shield I didn't managed to make it work. I have created an install file in my main windows form application, which you can see in the below code.
public partial class DeployInstaller : System.Configuration.Install.Installer
{
System.Data.SqlClient.SqlConnection masterConnection = new System.Data.SqlClient.SqlConnection();
public DeployInstaller()
{
InitializeComponent();
}
private string GetSql(string Name)
{
try
{
// Gets the current assembly.
Assembly Asm = Assembly.GetExecutingAssembly();
// Resources are named using a fully qualified name.
Stream strm = Asm.GetManifestResourceStream(Asm.GetName().Name + "." + Name);
// Reads the contents of the embedded file.
StreamReader reader = new StreamReader(strm);
return reader.ReadToEnd();
}
catch (Exception ex)
{
//Interaction.MsgBox("In GetSQL: " + ex.Message);
throw ex;
}
}
private void ExecuteSql(string Sql)
{
masterConnection.ConnectionString = "data source=.//SQLEXPRESS;initial catalog=master;integrated security=True; MultipleActiveResultSets=True; Application Name=EntityFramework";
System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand(Sql, masterConnection);
// Initialize the connection, open it, and set it to the "master" database
Command.Connection.Open();
try
{
Command.ExecuteNonQuery();
}
finally
{
// Closing the connection should be done in a Finally block
Command.Connection.Close();
}
}
protected void AddDBTable()
{
try
{
// Creates the database.
//ExecuteSql("master", "CREATE DATABASE " + strDBName);
// Creates the tables.
ExecuteSql( GetSql("sql.txt"));
}
catch (Exception ex)
{
// Reports any errors and abort.
//Interaction.MsgBox("In exception handler: " + ex.Message);
throw ex;
}
}
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
AddDBTable();
}
}
Supposedly this piece of code provides the user with the ability of doing both the installation of the system and the corresponding database. For some reason only the system is being installed. When attempting to install the database, something is preventing from successfully completing. Unfortunately, I cannot pinpoint the reason why because it doesn't give out an error with the reason. It could be that its never being started or that I did something wrong.
Any guide would be appreciated.
Which is better to make sure that the db connection is closed if the execution fails?
try
{
using (var mySqlConnection = new MySqlConnection(DatabaseManagement.DatabaseConnectionString))
{
DatabaseManagement.DatabaseCommand = mySqlConnection.CreateCommand();
DatabaseManagement.DatabaseCommand.CommandText = "INSERT INTO lastlaptimes Values ('" + UserObject.UserName + "','" + _lastLapTime + "')";
mySqlConnection.Open();
DatabaseManagement.DatabaseCommand.ExecuteNonQuery();
}
}
catch (MySqlException exception)
{
Logger.Error(exception);
}
Or this:
using (var mySqlConnection = new MySqlConnection(DatabaseManagement.DatabaseConnectionString))
{
try
{
DatabaseManagement.DatabaseCommand = mySqlConnection.CreateCommand();
DatabaseManagement.DatabaseCommand.CommandText = "INSERT INTO lastlaptimes Values ('" + UserObject.UserName + "','" + _lastLapTime + "')";
mySqlConnection.Open();
DatabaseManagement.DatabaseCommand.ExecuteNonQuery();
}
catch (MySqlException exception)
{
mySqlConnection.Close();
Logger.Error(exception);
}
}
I'm having issue with too many connections against the db, and I'm wondering if my first approach is leading to the problem with the connections, as the code is called numerous times and a new connection is opened and fails again and increasing the connections by 1.
Thanks for any help.
The only difference between these is whether or not you are explicitly calling the Close statement (both have a using statement, which runs Dispose automatically).
So the real question here is - does Dispose close the connection or do you need to call it explicitly? I believe the answer is that Dispose will call this for you (see this question). What that means is either works well - pick whichever you favor (I suppose the first is technically one line less code...)
I am struggling a bit with this piece of C# code. Basically, what I'm trying to do is some kind of mechanism to check if, in first place, the user and password combination for my SQL server was correct, and then, check if the database exists.
The connection string would be like this:
connectionString =
"database=test;server=localhost;uid=" + usr.Text + ";pwd=" + pwd.Text;
The solution I'm trying to reach is one that can check the exception thrown and tell if it's about a wrong password, a wrong user, not found database, etcetera. I've seen the use of DbConnectionStringBuilder in some places but I'm not sure of how I should use it.
string connectionString = "database=test;server=localhost;uid=" + usr.Text + ";pwd=" + pwd.Text;
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
}
catch (SqlException ex)
{
switch (ex.Number)
{
case 4060: // Invalid Database
....
break;
case 18456: // Login Failed
....
break;
default:
....
break;
}
}
}
The full list of Sql Server exception numbers can be found by running
SELECT * FROM master.dbo.sysmessages
DbConnection.Open() will fail with invalid credentials.
In trying to write a simple C# ADO.NET application to connect to my database and manage project entries for my website, I've run into a strange problem that I can not find any information regarding. I've verified that my MySQL server is accepting remote connections, listening on port 3306, the username provided is valid, as is the password, and the hostname resolves correctly. However, when SqlConnection.Open is called, I receive a nonsensical exception.
System.ArgumentOutOfRangeException was unhandled
Non-negative number required.
Parameter name: count
Below is the code that invokes said error, specifically on the call to m_ActiveConnection.Open()
static public void OpenConnection(CConnectionDescription ConnectionDescription)
{
try
{
SqlConnectionStringBuilder ConnectionStringBuilder = new SqlConnectionStringBuilder();
ConnectionStringBuilder.DataSource = ConnectionDescription.Address + "," + ConnectionDescription.PortNumber;
ConnectionStringBuilder.UserID = ConnectionDescription.UserName;
ConnectionStringBuilder.Password = ConnectionDescription.Password;
ConnectionStringBuilder.NetworkLibrary = "DBMSSOCN";
if (m_ActiveConnection != null)
{
if (m_ActiveConnection.State != System.Data.ConnectionState.Closed)
{
m_ActiveConnection.Close();
}
m_ActiveConnection.ConnectionString = ConnectionStringBuilder.ConnectionString;
}
else
{
m_ActiveConnection = new SqlConnection(ConnectionStringBuilder.ConnectionString);
}
m_ActiveConnection.Open();
m_ActiveConnectionDescription = ConnectionDescription;
if (ConnectionChanged != null)
{
ConnectionChanged();
}
}
finally
{
// Error message
}
}
What can cause this exception? I'm not passing any parameters to open and the ConnectionString seems completely valid. I've checked the values of the CConnectionDescription my self. Any help would be appreciated.
As far as I know, SqlConnection is used to connect to SqlServer databases. You should be using MySqlConnection from "MySQL Connector/Net".