我编写了一个具有工作数据库连接的代码。我使用的是phpmyadmin,所以它是本地的。一切正常,除非它没有与数据库建立活动连接;它只是崩溃了。我已经尝试了一个检查连接的计时器,但它仍然崩溃。
到目前为止我的代码:
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;
using HPJFRMS;
namespace HPJFRMS
{
public partial class HomeFRM : Form
{
private string conn;
MySqlConnection connect;
string _naam = "";
Form _Loginfrm;
public HomeFRM(Form logFrom, string _name)
{
_Loginfrm = logFrom;
InitializeComponent();
lbWelkom.Text = "welkom " + _name;
_naam = _name;
}
private void HomeFRM_Load(object sender, EventArgs e)
{
tmCheck.Enabled = true;
}
private bool Todo_ophalen()
{
db_connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT `todo` FROM `user` WHERE `username` LIKE '" + _naam + "'";
cmd.Connection = connect;
MySqlDataReader tdOphalen = cmd.ExecuteReader();
if (tdOphalen.Read())
{
tbTodo.Text = tdOphalen.GetString(0);
connect.Close();
return true;
}
else
{
connect.Close();
return false;
}
}
private void db_connection()
{
try
{
conn = "Server=127.0.0.1;Database=users;Uid=root;Pwd=;";
connect = new MySqlConnection(conn);
connect.Open();
}
catch (MySqlException e)
{
tmCheck.Enabled = false;
this.Hide();
MessageBox.Show("Je bent offline! Het programma word afgesloten");
this.Close();
}
finally
{
lbStatus.ForeColor = Color.Red;
}
}
private void btBewerk_Click(object sender, EventArgs e)
{
if (btBewerk.Text == "Bewerken")
{
tbTodo.ReadOnly = false;
btBewerk.Text = "Opslaan";
}
else
{
tbTodo.ReadOnly = true;
btBewerk.Text = "Bewerken";
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Dispose();
}
private void tmCheck_Tick(object sender, EventArgs e)
{
bool T = Todo_ophalen();
if (T)
{
lbStatus.ForeColor = Color.Green;
lbStatus.Text = "Online";
}
else
{
lbStatus.ForeColor = Color.Red;
lbStatus.Text = "Offline";
}
}