c#怎么连接数据库 用MySQL 详解

2024-11-27 10:50:54
推荐回答(5个)
回答1:

1、mysql官网下载 .net连接器

2、引用下载后的mysql.data.dll

3、程序开始加:using MySql.Data.MySqlClient;

4、连接数据库:

  private void button1_Click(object sender, EventArgs e)//登入按钮
        {
            string power = comboBox1.Text.Trim();
            string user = textBox1.Text.Trim();
            string psd = textBox2.Text.Trim();
            string ipaddress = "";
            string mysqluser = "";
            string mysqlpsd = "";

            if (user == "")
            {
                MessageBox.Show("请输入用户名");
            }
            else if (psd == "")
            {
                MessageBox.Show("请输入密码");
            }
            else
            {
                try
                {
                    try
                    {
                        string[] getconfig = File.ReadAllLines("E:/project/configure.txt", Encoding.GetEncoding("gb2312"));
                        ipaddress = getconfig[0].Split(':')[1];//读取ip地址
                        mysqluser = getconfig[1].Split(':')[1];//读取数据库账号
                        mysqlpsd = getconfig[2].Split(':')[1]; //读取数据库密码       
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("配置文件丢失");
                        return;
                    }

                    string query = "SET names gb2312;SELECT COUNT(id) FROM fx_user WHERE name='" + user + "' AND password=MD5('" + psd + "') AND userid='" + power + "'";
                    MySqlConnection cn = new MySqlConnection("server=" + ipaddress + ";user id=" + mysqluser + ";Password=" + mysqlpsd + ";database=system;charset=gb2312");
                 
                cn.Open();
                    MySqlCommand cm = new MySqlCommand(query, cn);
                    MySqlDataReader read = cm.ExecuteReader();      //搜索满足 用户名,密码,操作员的记录。
                    //如果记录没有-->密码或用户名错误
                    if (read.Read())                                //如果记录多余1条-->数据错误,联系管理员
                    {                                               //只有一条记录则成功登入
                        int x = Int32.Parse(read[0].ToString());
                        if (x == 0)
                        {
                            MessageBox.Show("用户名或密码错误");
                        }
                        else if (x > 1)
                        {
                            MessageBox.Show("用户冲突,请联系管理员");
                        }
                        else if (x == 1)
                        {
                            //  MessageBox.Show("登入成功");
                            main mf = new main(power, ipaddress, mysqluser, mysqlpsd);   //将操作员 和 IP地址传入 主窗体 

                            mf.Show();
                            this.Hide();
                            cn.Close();
                        }
                    }
                }
                catch (MySql.Data.MySqlClient.MySqlException ex)
                {
                    switch (ex.Number)
                    {
                        case 0:
                            MessageBox.Show("数据库连接失败1");
                            break;
                        case 1045:
                            MessageBox.Show("数据库密码或用户名错误");
                            break;
                        default:
                            MessageBox.Show("数据库连接失败2");
                            break;
                    }
                }
            }
        }

回答2:

c#连接MySql数据库的方法
一、用MySQLDriverCS连接MySQL数据库。
先下载和安装MySQLDriverCS,在安装文件夹下面找到MySQLDriver.dll,然后将MySQLDriver.dll添加引用到项目中。

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 MySQLDriverCS;
namespace jxkh
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{

MySQLConnectionString tConnStr = new MySQLConnectionString("10.14.55.46", "performance", "administrator", "1234567@byd", 3306);
MySQLConnection tConn = new MySQLConnection(tConnStr.AsString);
try
{
tConn.Open(); //打开连接
MySQLCommand cmd4 = new MySQLCommand("set names gb2312", tConn);
cmd4.ExecuteNonQuery();
string tCmd = "select ID,Name,PassWord from managers"; //命令语句
MySQLCommand cmd = new MySQLCommand(tCmd,tConn); //在定义的tConn对象上执行查询命令
MySQLDataReader tReader = cmd.ExecuteReaderEx();
if(tReader.Read()) // 一次读一条记录
{
if(tReader["Name"].ToString()==textBox1.Text&&tReader["PassWord"].ToString()==textBox2.Text)
{
frmJxkh myJxkh = new frmJxkh();
myJxkh.Show();
}
}
tConn.Close();//重要!要及时关闭
tReader.Close();

}
catch
{
tConn.Close();
}

}
}
}

二、通过ODBC访问mysql数据库:
1. 安装Microsoft ODBC.net;
2. 安装MDAC 2.7或者更高版本;
3. 安装MySQL的ODBC驱动程序;
4. 管理工具 -> 数据源ODBC –>配置DSN…;
5. 解决方案管理中添加引用 Microsoft.Data.Odbc.dll(1.0.3300);
6. 代码中增加引用 using Microsoft.Data.Odbc;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq; //vs2005好像没有这个命名空间,在c#2008下测试自动生成的
using System.Text;
using System.Windows.Forms;
using Microsoft.Data.Odbc;

namespace mysql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" +
"SERVER=localhost;" +
"DATABASE=inv;" +
"UID=root;" +
"PASSWORD=831025;" +
"OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
MyConnection.Open();
Console.WriteLine(""n success, connected successfully !"n");

string query = "insert into test values( 'hello', 'lucas', 'liu')";
OdbcCommand cmd = new OdbcCommand(query, MyConnection);

//处理异常:插入重复记录有异常
try{
cmd.ExecuteNonQuery();
}
catch(Exception ex){
Console.WriteLine("record duplicate.");
}finally{
cmd.Dispose();
}

//***********************用read方法读数据到textbox**********************
string tmp1 = null;
string tmp2 = null;
string tmp3 = null;
query = "select * from test ";
OdbcCommand cmd2 = new OdbcCommand(query, MyConnection);
OdbcDataReader reader = cmd2.ExecuteReader();
while (reader.Read())
{
tmp1 = reader[0].ToString();
tmp2 = reader[1].ToString();
tmp3 = reader[2].ToString();
}
this.textBox1.Text = tmp1 + " " + tmp2 + " " + tmp3;
*/

//************************用datagridview控件显示数据表**************************
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" +
"SERVER=localhost;" +
"DATABASE=inv;" +
"UID=root;" +
"PASSWORD=831025;" +
"OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
OdbcDataAdapter oda = new OdbcDataAdapter("select * from customer ", MyConnection);
DataSet ds = new DataSet();

oda.Fill(ds, "employee");
this.dataGridView1.DataSource = ds.Tables["employee"];
*/

MyConnection.Close();
}
}
}

回答3:

 
  1. usingSystem;  
  2. usingSystem.Collections.Generic;  
  3. usingSystem.ComponentModel;  
  4. usingSystem.Data;  
  5. usingSystem.Data.Odbc;  
  6. usingSystem.Drawing;  
  7. usingSystem.Linq;  
  8. usingSystem.Text;  
  9. usingSystem.Windows.Forms;  
  10. usingMySQLDriverCS;  
  11. namespacemysql{  
  12. publicpartialclassForm1:Form{  
  13. publicForm1(){  
  14. InitializeComponent();  
  15. }  
  16. privatevoidForm1_Load(objectsender,EventArgse){  
  17. MySQLConnectionconn=null;  
  18. conn=newMySQLConnection(newMySQLConnectionString
    ("localhost","inv","root","831025").AsString);  
  19. conn.Open();  
  20. MySQLCommandcommn=newMySQLCommand("setnamesgb2312",conn);  
  21. commn.ExecuteNonQuery();  
  22. stringsql="select*fromexchange";  
  23. MySQLDataAdaptermda=newMySQLDataAdapter(sql,conn);  
  24. DataSetds=newDataSet();  
  25. mda.Fill(ds,"table1");  
  26. this.dataGrid1.DataSource=ds.Tables["table1"];  
  27. conn.Close();  
  28. }  
  29. }  

把你的数据库名称修改下就行了(18行处),另,个人做法,把连接代码保存在一个文件中备用,随用随拷。

回答4:

引用MySql.Data.dll库连接MySQL

回答5:

提供参考的代码
public class StudentService
{

//从配置文件中读取数据库连接字符串
private readonly static string connString = ConfigurationManager.ConnectionStrings["accpConnectionString"].ToString();

AdoNetModels.Student model = new Student();

#region 删除数据1
public int DeleteStudent(int stuID)
{
int result = 0;
// 数据库连接 Connection 对象
SqlConnection connection = new SqlConnection(connString);
// 构建删除的sql语句
string sql = string.Format("Delete From Student Where stuID={0}", stuID);
// 定义command对象
SqlCommand command = new SqlCommand(sql, connection);

try
{
connection.Open();
result = command.ExecuteNonQuery(); // 执行命令
}
catch (Exception ex)
{

Console.WriteLine(ex.Message);
}
finally
{
connection.Close();
}
return result;
}
#endregion

}