Click here to Skip to main content
15,886,714 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
I made a Mysql Database and a sign-up form for a chat app but it's not connecting with the database.

What I have tried:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
        private MySqlConnection connection;
        private string server;
        private string database;
        private string uid;
        private string password;

        public Form1()
        {
            InitializeComponent();

            server = "localhost";
            database = "ddata_db";
            uid = "robot";
            password = "qwerty";

            string connectionString;
            connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

            connection = new MySqlConnection(connectionString);
        }

        private bool OpenConnection()
        {
            try
            {
                connection.Open();
                return true;
            }
            catch (MySqlException ex)
            {
                switch (ex.Number)
                {
                    case 0:
                        MessageBox.Show("Connection to Server failed");
                        break;
                    case 1045:
                        MessageBox.Show("Server username or password incorrect");
                        break;
                }
                return false;
            }
        }

        private bool CloseConnection()
        {
            try
            {
                connection.Open();
                return true;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        private void btnRegister_Click(object sender, EventArgs e)
        {
            string Fname = txtfullname.Text;
            string Uname = txtusername.Text;
            string Email = txtemail.Text;
            string Pass = txtpassword.Text;

            if (Register(Fname, Uname, Email, Pass))
            {
                MessageBox.Show("User has been Created");
            }
            else
            {
                MessageBox.Show("User has not been Created");
            }
        }

        public bool Register(String Fname, String Uname, String Email, String Pass)
        {
            string query = "INSERT INTO users (Uid,Fullname,Username,Email,Password) VALUES ('','Fname','Uname','Email','Pass');";

            try
            {
                if (OpenConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, connection);
                    try
                    {
                        cmd.ExecuteNonQuery();
                        return true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return false;
                    }
                }
                else
                {
                    connection.Close();
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                connection.Close();
                return false;
            }
        }
    }
}
Posted
Updated 16-Sep-18 18:31pm
Comments
phil.o 16-Sep-18 4:42am    
How can we know?
OriginalGriff 16-Sep-18 5:00am    
This is not a good question - we cannot work out from that little what you are trying to do.
Remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with. So tell us what errors you get, what you did to get them, what you have done to find out what causes them. What does teh debugger show is happening?

Use the "Improve question" widget to edit your question and provide better information.
[no name] 16-Sep-18 20:33pm    
What is your table structure in the database and what is your problem that you are reporting/troubleshooting? Do you get any errors, if so where? And what are they?
Richard Deeming 18-Sep-18 15:39pm    

1 solution

Try this, but you need to change your connection string to your own. I have made many comments inline so I will keep this post to a minimum. If it helps, mark it as your answer. Any questions let me know. I've fixed a number of mistakes and commented some of them.

I've changed a lot of your code, and although I didn't write you a properly structured reusable robust class, as I didn't have time, but you should learn to utilise class development to your advantage, as you can make a lot of reusable code by doing so. Your problem is fixed for the most part.

Screenshot: https://prnt.sc/kv84hb[^]
C#
using MySql.Data.MySqlClient; //Make sure this using directive is applied and reference your MySQL DLL to your project.
using System;
using System.Data;
using System.Windows.Forms;

namespace TestCSharpApp
{
    public partial class Form1 : System.Windows.Forms.Form
    {   //This is my connection string, and its working. I suggest you build yours the same way
        //Or consider using string builder to build your string
        private static string cString = "server=localhost;user id=root;password=root;persistsecurityinfo=True;database=visuals_db;port=3306";
        private static MySqlConnection Con = new MySqlConnection(cString);
        ////private static string server = "localhost";
        ////private static string database = "visuals_db";
        ////private static string uid = "root";
        ////private static string password = "root";

            //You don't need all these strings. Use the one string.

        public Form1()
        {
            InitializeComponent();//Do not use this method to store junk.
            //If you want to create new strings on load, use the form load event.
        }
        private void btnRegister_Click(object sender, EventArgs e)
        {
            string Fname = "John doe";
            string Uname = "JohnDoe1";
            string Email = "me@myemail.com";
            string Pass = "mypass123";

            if (Register(Fname, Uname, Email, Pass))
            {
                MessageBox.Show("User has been Created");
            }
            else
            {
                MessageBox.Show("User has not been Created");
            }
        }

        public bool Register(String Fname, String Uname, String Email, String Pass)
        {
            string execQuery = "INSERT INTO users (name,username,email,password) VALUES (@Fname,@Uname,@Email,@Pass)";
            //Remove your unnecessary ''''''' in values and don't encapsulate ; inside the querry.
            try //Do not nest try catch blocks, except, declare more than one catch exception
            {
                if (Con != null && Con.State == ConnectionState.Closed)
                    //Check connection is not null and open it if its closed.
                {
                    Con.Open();//Open con
                    using (MySqlCommand cmd = new MySqlCommand(execQuery, Con))
                    {//Use using blocks for disposable code
                        cmd.Parameters.AddWithValue("@Fname", Fname);
                        cmd.Parameters.AddWithValue("@Uname", Uname);
                        cmd.Parameters.AddWithValue("@Email", Email);
                        cmd.Parameters.AddWithValue("@Pass", Pass);
                        //Use parameterized command queries.
                        cmd.ExecuteNonQuery();
                        //Use add with value since add is depreciated
                    }
                    Con.Close();
                    //Remember to manually close the connection since we removed the unnecessary functions
                    return true;
                }
                return true;
            }
            catch (NullReferenceException nullRefEx)
            {
                MessageBox.Show(nullRefEx.Message);
                Con.Close(); //Check your connection state before attempting to open/close.
                return false;
            }
            catch (MySqlException sqlErr)
            { // handle your second error here
                return false;
            }
            catch (Exception ex)
            {//Then catch all errors you might miss?
                return false;
            }
            finally
            {//https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-finally
                //Finish your statements if any cleaning up needed etc...
            }
        }
    }
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900