为什么它不与mysql数据库连接 [英] Why it is not connecting with mysql database
本文介绍了为什么它不与mysql数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我为聊天应用创建了一个Mysql数据库和一个注册表单,但它没有与数据库连接。
我尝试过:
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;
}
}
}
}
推荐答案
试试这个,但是你需要将您的连接字符串更改为您自己的。我已经内联了很多评论,所以我会把这篇文章保持在最低限度。如果有帮助,请将其标记为您的答案。有任何问题让我知道。我修正了一些错误并对其中的一些进行了评论。
我已经改变了很多代码,虽然我没有给你写好结构化的可重用的健壮类,因为我没有时间,但你应该学会利用类开发来获得优势,因为你可以通过这样做来制作大量可重用的代码。你的问题大部分是固定的。
截图: https://prnt.sc/kv84hb [ ^ ]
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[^]
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 (id,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...
}
}
}
}
这篇关于为什么它不与mysql数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文