using MySql.Data.MySqlClient;
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;
namespace WindowsFormsApp1
{
public partial class Form2 : Form
{
private string account = "";
public DataTable GetDataTable(string sql)
{
MySqlConnection conn = new MySqlConnection("server=localhost;user id=root;password=123456;database=jian");
MySqlCommand cmd = conn.CreateCommand();//命令对象(用来封装需要在数据库执行的语句)
cmd.CommandText = sql;//设置sql文本
//第一种方式,用数据适配器
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);//这里也可以把数据查询结果填充到DataSet中
return dt;
}
/// <summary>
/// 建立数据库连接.
/// </summary>
/// <returns>返回MySqlConnection对象</returns>
public MySqlConnection getmysqlcon()
{
try
{
string M_str_sqlcon = "server=127.0.0.1;user=root;password=123456;database=jian"; //根据自己的设置
MySqlConnection myCon = new MySqlConnection(M_str_sqlcon);
return myCon;
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
return null;
}
}
/// <summary>
/// 创建一个MySqlDataReader对象
/// </summary>
/// <param name="M_str_sqlstr">SQL语句</param>
/// <returns>返回MySqlDataReader对象</returns>
public MySqlDataReader getmysqlread(string M_str_sqlstr)
{
MySqlConnection mysqlcon = this.getmysqlcon();
MySqlCommand mysqlcom = new MySqlCommand(M_str_sqlstr, mysqlcon);
mysqlcon.Open();
MySqlDataReader mysqlread = mysqlcom.ExecuteReader();
return mysqlread;
}
public Form2()
{
InitializeComponent();
}
public Form2(string account)
{
this.account = account;
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
this.Hide();
}
private void Form2_Load(object sender, EventArgs e)
{
string sql = string.Format("select msg from updatemsg where account = '{0}' ", this.account);
DataTable result = GetDataTable(sql);
comboBoxMsg.DisplayMember = "msg";
comboBoxMsg.ValueMember = "msg";
comboBoxMsg.DataSource = result;
//string sql = string.Format("select msg from updatemsg where account = '{0}' ", this.account);
//MySqlDataReader result = getmysqlread(sql);
//while (result.Read()) {
// comboBoxMsg.Items.Add(result[0].ToString());
//}
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBoxMsg.Text != null) {
string sql = string.Format("UPDATE updatemsg SET msg='{0}' where account = '{1}' and msg = '{2}' ", textBoxUpdate.Text, this.account,comboBoxMsg.Text);
MessageBox.Show(sql);
MySqlDataReader result = getmysqlread(sql);
}
}
private void Form2_VisibleChanged(object sender, EventArgs e)
{
string sql = string.Format("select msg from updatemsg where account = '{0}' ", this.account);
DataTable result = GetDataTable(sql);
comboBoxMsg.DisplayMember = "msg";
comboBoxMsg.ValueMember = "msg";
comboBoxMsg.DataSource = result;
//while (result.Read())
//{
// comboBoxMsg.Items.Add(result[0].ToString());
//}
}
}
}