将C#连接到MySQL
我有一些小程序的代码。所以我想把数据发送到MYSQL数据库。这是我的代码,它在一个dll文件中。所以我需要在我的GUI应用程序中调用它。这是连接代码(dll代码) 这是GUI代码将C#连接到MySQL,c#,mysql,.net,C#,Mysql,.net,我有一些小程序的代码。所以我想把数据发送到MYSQL数据库。这是我的代码,它在一个dll文件中。所以我需要在我的GUI应用程序中调用它。这是连接代码(dll代码) 这是GUI代码 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; usin
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using codeSnips;
using connectionManager;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
getAnswers obj1 = new getAnswers();
DBConnect dbconnect = new DBConnect();
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure?", "Warrning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
this.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
DateTime date1 = dtp1.Value.Date;
DateTime date2 = dtp2.Value.Date;
TimeSpan result = obj1.getdateDiffrance(date1, date2);
txt1.Text = result.ToString(@"dd");
}
private void button2_Click(object sender, EventArgs e)
{
float dayfee = float.Parse(txt2.Text);
int alldays = int.Parse(txt1.Text);
float totfee = obj1.totalFeePayble(dayfee,alldays);
txt3.Text = totfee.ToString();
}
private void button4_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
}
private void button5_Click(object sender, EventArgs e)
{
dbconnect.OpenConnection();
}
}
}
那么我如何调用数据库打开函数呢?首先,如果您是从另一个类调用
DBConnect
,则需要将其公开:
public class DBConnect {...}
您还需要将方法OpenConnection
和CloseConnection
公开
public bool OpenConnection() {...}
public bool CloseConnection() {...}
如果只需要一个消息框,那么只需检查dbconnect.OpenConnection()
的返回值
像这样的东西会有用的,虽然这应该是很基本的东西
private void button5_Click(object sender, EventArgs e)
{
if (dbconnect.OpenConnection())
{
MessageBox.Show("Connection Opened Successfully!");
}
else
{
MessageBox.Show("Connection Failed!");
}
}
或者你也可以用三元来减少代码量
private void button5_Click(object sender, EventArgs e)
{
dbconnect.OpenConnection() ?
MessageBox.Show("Connection Opened Successfully") :
MessageBox.Show("Connection Failed!");
}
原因如下:
在DBConnect
类中,函数OpenConnection
返回类型为bool
的值。因此,当您对dbconnect
对象调用方法时,如果连接打开,它将返回true
,如果连接尝试期间出现异常,它将返回false
。因此,dbconnect.OpenConnection()
根据该方法的执行结果,要么等于true,要么等于false。我们在按钮5中检查该值,然后单击(…)
瞧
以下几点提示:
Initialize()。“Initialize”这个名字并不是一个很好的做法,其他阅读你的代码的人通过查看它不会知道它做了什么
int
,因此您可以从GUI中检查错误代码,并根据需要在其中放置尽可能多的MessageBox
你有什么问题?我在您的第一个代码示例中看到一个连接字符串,当您单击按钮5时,您正在调用“OpenConnection”,那么问题出在哪里?我想显示消息框,看看连接是否正常,您是否只是从中复制粘贴代码?你应该做更多的研究,比如阅读手册。请看:我已经在@user2751419编辑了几次我的答案,请确保您检查了新内容;)谢谢你的提示这对我很有用
private void button5_Click(object sender, EventArgs e)
{
dbconnect.OpenConnection() ?
MessageBox.Show("Connection Opened Successfully") :
MessageBox.Show("Connection Failed!");
}