C#winform三层中如何进行数据库连接的测试
1个回答
展开全部
C#连接mysql用法与sqlclient里的自带函数一样。
注意:要在添加引用里引用 Mysql.Data
具体代码如下
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;using System.Data.SqlClient;using MySql.Data.MySqlClient; namespace importTxtToMysql{ public partial class Form2 : Form { private DataSet dsall; //private static String mysqlcon = "Data Source=MySQL;database=onepc;Password=;User ID=root;Location=192.168.1.168;charset=utf8"; private static String mysqlcon = "database=onepc;Password=;User ID=root;server=192.168.1.168";//Data Source=MySQL;;charset=utf8"; private MySqlConnection conn; private MySqlDataAdapter mdap; public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { // MySqlCommand cmd = new MySqlCommand("select "); mdap = new MySqlDataAdapter("select * from allhard",conn); dsall = new DataSet(); mdap.Fill(dsall,"hard"); dataGridView1.DataSource = dsall.Tables["hard"]; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { } } private void Form2_Load(object sender, EventArgs e) { conn = new MySqlConnection(mysqlcon); } }}
注意:要在添加引用里引用 Mysql.Data
具体代码如下
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;using System.Data.SqlClient;using MySql.Data.MySqlClient; namespace importTxtToMysql{ public partial class Form2 : Form { private DataSet dsall; //private static String mysqlcon = "Data Source=MySQL;database=onepc;Password=;User ID=root;Location=192.168.1.168;charset=utf8"; private static String mysqlcon = "database=onepc;Password=;User ID=root;server=192.168.1.168";//Data Source=MySQL;;charset=utf8"; private MySqlConnection conn; private MySqlDataAdapter mdap; public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { // MySqlCommand cmd = new MySqlCommand("select "); mdap = new MySqlDataAdapter("select * from allhard",conn); dsall = new DataSet(); mdap.Fill(dsall,"hard"); dataGridView1.DataSource = dsall.Tables["hard"]; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { } } private void Form2_Load(object sender, EventArgs e) { conn = new MySqlConnection(mysqlcon); } }}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询