Connecting C# to MYSQL database? - c#

So i been trying to connect C# windows from to MYSQL database, i tryed many different methods that i found online but none seems to be working. here is my code please help (keep in mind this is the first time i use database before).
Here is the connecting class
class DbConnect
{
public static void DBConnect()
{
string connstr =
"server=localhost;user=root;database=login;port=3306;password=Password";
MySqlConnection conn = new MySqlConnection(connstr);
try
{
conn.Open();
}
catch
{
Console.WriteLine("went rong");
}
}
}
Here is the windows form im using
private void btnenter_Click(object sender, EventArgs e)
{
DbConnect.DBConnect();
MySqlCommand query = new MySqlCommand("INSERT INTO logininfo (username,
password) VALUES(#username, #password");
try
{
query.Parameters.AddWithValue("#username", txtusername.Text);
query.ExecuteNonQuery();
MessageBox.Show("S");
}
catch (Exception )
{
MessageBox.Show("something went wrong");
}
finally
{
DbConnect.DBClose();
}
}

User is passed in MySQL connection string using Uid. So your connection string should be like:
"server=localhost;Uid=root;database=login;port=3306;password=tro63jans";
You may see: MySQL connection string.
You should also catch exception in some object, so that you can get the details about the exception. Currently you are not showing any useful message from your exception.
catch (Exception ex) //at least
{
MessageBox.Show("something went wrong: " + ex.ToString());
}

One problem you have here is you're not setting the Connection property of your MysqlCommand to the MySqlConnection you're making earlier.
Change DBConnect() to return your MySqlConnection.
Set your MySqlCommand's Connection property to the returned value.
PSEUDO-CODE
MySqlConnection conn = DBConnect.DBConnect();
MySqlCommand command = new MySqlCommand(commandStr, conn);
command.ExecuteNonQuery();
conn.Close();

Related

File Not Found Exception was unhandled in the line of adapter.Fill(table)

Im trying to connect to the database MySql but this error was appeared
FileNotFoundException was unhandled
in the line of adapter.Fill.
FileNotFoundException was unhandled Could not load file or assembly 'Renci.SshNet, Version=2016.1.0.0, Culture=neutral, PublicKeyToken=1cee9f8bde3db106' or one of its dependencies. The system cannot find the file specified
class CONNECT
{
private MySqlConnection connection = new MySqlConnection("Datasource=localhost;Port=3306;Username=root;Password=;Database=Csharp_Hotel_DB");
//create a function to return our connection
public MySqlConnection getConnection()
{
return connection;
}
//create a function to open the connection
public void openConnection()
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
}
//create a function to close the connection
public void closeConnection()
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
private void buttonLogin_Click(object sender, EventArgs e)
{
CONNECT conn = new CONNECT();
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand();
String query = "SELECT * FROM `users` WHERE `username`=#usn AND `password`=#pass";
command.CommandText = query;
command.Connection = conn.getConnection();
command.Parameters.Add("#usn", MySqlDbType.VarChar).Value = textBoxUsername.Text;
command.Parameters.Add("#pass", MySqlDbType.VarChar).Value = textBoxPassword.Text;
adapter.SelectCommand = command;
adapter.Fill(table); //this line is the FileNotFoundException was unhandled
// if the username and the password exists
if (table.Rows.Count > 0)
{
this.Hide();
MessageBox.Show("YES");
Main_Form mform = new Main_Form();
mform.Show();
}
else
{
if (textBoxUsername.Text.Trim().Equals(""))
{
MessageBox.Show("Enter Your Username to Login", "Empty Username", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (textBoxPassword.Text.Trim().Equals(""))
{
MessageBox.Show("Enter Your Password to Login", "Empty Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Username and Password Doesn't Exists", "Wrong Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
It's now working c.
Using the MySQL-connector-net-6.3.5 can fix this error or problem because I'm using .net 4
Thank you for your help.
it seems that you do not handle the exceptions adapter.fill could through.
use:
try{
adapter.Fill(table);
} catch(FileNotFoundException e) {
do stuff with e or your code
}
alternatively check the pathes if they exist before using them.
You are creating a data table without passing a name into the constructor. This means that the table is nameless and so when you try to call Fill on a nameless table you get your file not found exception.
You should pass in the table name
DataTable table = new DataTable("users");
This is a bug in MySQL Connector/NET, bug 96614. It will be fixed in Connector/NET 8.0.18.
Fixed as of the upcoming MySQL Connector/NET 8.0.18 release, and here's the changelog entry:
The Renci.SshNet.dll deployment was problematic for Connector/NET 8.0.17
MSI installations. Some applications, such as Microsoft Excel, were unable
to read MySQL data as a result. This fix removes unnecessary dependencies
on the DLL and also ensures that the MSI installation deploys the correct
Renci.SshNet.dll to the GAC.
A workaround you can use today is switching to MySqlConnector, an alternative OSS ADO.NET library for MySQL, which doesn't have this bug.

SQL helper class - two connection strings

I have the following SQL helper class:
public class SqlHelper
{
SqlConnection cn;
public SqlHelper(string connectionString)
{
cn = new SqlConnection(connectionString);
}
public bool isConnection
{
get
{
if (cn.State == System.Data.ConnectionState.Closed)
cn.Open();
return true;
}
}
}
I also have two connection strings:
string connectionString = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", Variables.setDb1ServerName, Variables.setDb1Name, Variables.setDb1User, Variables.setDb1Password);
string connectionString2 = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", Variables.setDb2ServerName, Variables.setDb2Name, Variables.setDb2User, Variables.setDb2Password);
What I want to do is create two buttons that will check if the respective connection is active.
My attempt is below - button one:
private void txtConnection1_Click(object sender, EventArgs e)
{
string connectionString = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", Variables.setDb1ServerName, Variables.setDb1Name, Variables.setDb1User, Variables.setDb1Password);
try
{
SqlHelper helper = new SqlHelper(connectionString);
if (helper.isConnection)
MessageBox.Show("Конекцијата е успешна", "Порака", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Порака", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I've also create a second button, that connects to ConnectionString2 with SqlHelper helper2 = new SqlHelper(connectionString);
The code compiled alright. But I'm getting errors in the actual usage. One of the connections is diagnosed as active, while the second one produces a error.
Why question is.. can I reference two connection strings to a single sql helper class? If yes, any ideas where I might be making a mistake?
Update:
So this is the error that I am receiving. But if I restart the application and try the same connection first, I will be receiving a positive indicator.

ADO.NET programming says error occured - ExecuteNonQuery requires an open and available connection

Right now, my professor requires me to implement a case study using ADO.NET to save data into SQL Server. I have already created a database and tables in SQL Server and I'm trying to create some forms in Visual Studio by C# ADO.NET. I write according to a YouTube video. But I don't know why I cannot save my data to database successfully.
The result as I write my code like this.
Any help would be appreciated.
namespace casestudy
{
public partial class Form2 : Form
{
SqlConnection vcon2 = new SqlConnection(#"Data Source=SOPHIA-PC\SQLEXPRESS;Initial Catalog=casestudy;Integrated Security=True");
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
try
{
vcon2.Open();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
this.Dispose();
}
}
private void button1_Click(object sender, EventArgs e)
{
string vsql = string.Format("insert into Calluser values ({0}, '{1}', '{2}', {3})", Int32.Parse(txtUserID.Text), txtFName.Text, txtLName.Text, Int32.Parse(txtZoneID.Text));
SqlCommand vCom = new SqlCommand(vsql, vcon2);
try
{
vCom.ExecuteNonQuery();
vCom.Dispose();
MessageBox.Show("The User Information stored.");
txtZoneID.Text = "";
txtLName.Text = "";
txtFName.Text = "";
txtUserID.Text = "";
txtUserID.Focus();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
this.Dispose();
}
}
}
}
Can you add a check to see if the connection is actually open and if not reopen it just before you call the ExecuteNonQuery()
if (vcon2.State != ConnectionState.Open)
{
vcon2.Open();
}
vCom.ExecuteNonQuery();
Opening the connection when the application or form opens is probably not the best approach. You want to open the connection right before you execute your sql and close it as soon as possible.
That being said, I recommend removing the code from the Form2_Load event. And do everything in the button1_Click or another method you call from there. Even better would be to have a class or component that does the data access for your application. Also use a using statement as it will ensure resources are disposed even if an exception is thrown.
using (SqlConnection connection = new SqlConnection(#"Data Source=SOPHIA-PC\SQLEXPRESS;Initial Catalog=casestudy;Integrated Security=True");))
{
SqlCommand command = new SqlCommand(vsql, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
Some info on the using statement:
http://www.dotnetperls.com/using
https://msdn.microsoft.com/en-us/library/yh598w02.aspx

SQL Server : reconnect after lost connection

I want open WPF program, then SQL Server database is off and when database is back online, WPF should auto connect to the database. If I restart SQL Server, keep alive program and try connect to database until connection is available. Should I catch the exception and then repeat something?
I try restart application then I got exception, but anyway my program crash and stop working.
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
}
catch (SqlException ex)
{
//how stop crash? //
//System.Windows.Forms.Application.Restart();
return ex.ToString();
}
finally
{
connection.Close();
}
}
The thing to do is to centralize the creation of connections in a single static method for your entire application.
public static SqlConnection getConnection()
{
string conn = string.Empty;
conn = System.Configuration.ConfigurationManager.ConnectionStrings["quality"].ConnectionString;
SqlConnection aConnection = new SqlConnection(conn);
return aConnection;
}
In your code,every time you use a connection try this :
public int test()
{
SqlConnection conn = null;
try
{
try
{
conn = StaticContext.getConnection();
conn.Open();
//TODO OPERATION
}
catch (Exception e)
{
//return ex.ToString();
return -1;//MY_ERROR_CODE;
}
}
finally
{
conn.Close();
}
return 1//MY_SUCCES_CODE;
}
When you call DB method manage so the error:
if (test() == -1)
{
//MESSAGE BOX ERROR OR OTHER
}

Why are there connections open to my databases?

I have a program that stores user projects as databases. Naturally, the program should allow the user to create and delete the databases as they need to. When the program boots up, it looks for all the databases in a specific SQLServer instance that have the structure the program is expecting. These database are then loaded into a listbox so the user can pick one to open as a project to work on.
When I try to delete a database from the program, I always get an SQL error saying that the database is currently open and the operation fails. I've determined that the code that checks for the databases to load is causing the problem. I'm not sure why though, because I'm quite sure that all the connections are being properly closed.
Here are all the relevant functions. After calling BuildProjectList, running "DROP DATABASE database_name" from ExecuteSQL fails with the message: "Cannot drop database because it is currently in use". I'm using SQLServer 2005.
private SqlConnection databaseConnection;
private string connectionString;
private ArrayList databases;
public ArrayList BuildProjectList()
{
//databases is an ArrayList of all the databases in an instance
if (databases.Count <= 0)
{
return null;
}
ArrayList databaseNames = new ArrayList();
for (int i = 0; i < databases.Count; i++)
{
string db = databases[i].ToString();
connectionString = "Server=localhost\\SQLExpress;Trusted_Connection=True;Database=" + db + ";";
//Check if the database has the table required for the project
string sql = "select * from TableExpectedToExist";
if (ExecuteSQL(sql)) {
databaseNames.Add(db);
}
}
return databaseNames;
}
private bool ExecuteSQL(string sql)
{
bool success = false;
openConnection();
SqlCommand cmd = new SqlCommand(sql, databaseConnection);
try
{
cmd.ExecuteNonQuery();
success = true;
}
catch (SqlException ae)
{
MessageBox.Show(ae.Message.ToString());
}
closeConnection();
return success;
}
public void openConnection()
{
databaseConnection = new SqlConnection(connectionString);
try
{
databaseConnection.Open();
}
catch(Exception e)
{
MessageBox.Show(e.ToString(), "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void closeConnection()
{
if (databaseConnection != null)
{
try
{
databaseConnection.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
The SqlConnection class polls the actual database connection. If you close the SqlConnection, the connection is returned to the Connection pool. To prevent this behaviour, set SqlConnection.Pooling = false;.
edit
John seems to be more to the point here. But you might have to keep polling in mind as well.
Two comments. First off, you should use a using statement and your could will be much cleaner.
More on topic, you are connecting to the database when you are trying to drop it! Connect to the master database instead.

Categories