0

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(); } } 
2
  • 1
    Don't you have to assign the connection to the MySqlCommand object? Commented Apr 3, 2014 at 20:30
  • Show us what you tried so far and what specific problems you encountered. Commented May 3, 2014 at 2:25

2 Answers 2

2

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()); } 
Sign up to request clarification or add additional context in comments.

2 Comments

Ok so i changes the uid and still did not work, im making the exception now to see what else is wrong
Connection must be vail and open is what its saying, so something is wrong with the connection
1

One problem you have here is you're not setting the Connection property of your MysqlCommand to the MySqlConnection you're making earlier.

  1. Change DBConnect() to return your MySqlConnection.
  2. 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(); 

2 Comments

What type of return does it need, just a boolean?
No, it should return a MySqlConnection object (specifically your conn instance.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.