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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/*先下载和安装MySQLDriverCS,地址:
http://sourceforge.net/projects/mysqldrivercs/
在安装文件夹下面找到MySQLDriver.dll,然后将MySQLDriver.dll添加引用到项目中
* */
private void button1_Click(object sender, EventArgs e)
{
string findName = textBox2.Text.Trim();
textBox1.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
MySQLConnectionString tConnstr = new MySQLConnectionString("这里是mysql地址", "库名", "登录名", "密码");
MySQLConnection tConn = new MySQLConnection(tConnstr.AsString);
try
{
tConn.Open();
MySQLCommand cmd4 = new MySQLCommand("set names gb2312", tConn);
cmd4.ExecuteNonQuery();
string tCmd = "SELECT * FROM `mdl_user` WHERE `lastname`="+"\""+findName+"\"";
MySQLCommand cmd = new MySQLCommand(tCmd, tConn);
MySQLDataReader tReader = cmd.ExecuteReaderEx();
while(tReader.Read())
{
textBox1.AppendText(tReader["lastip"].ToString() + "\n");
textBox3.AppendText(tReader["username"].ToString()+"\n");
textBox4.AppendText(tReader["firstname"].ToString() + "\n");
textBox5.AppendText(tReader["password"].ToString() + "\n");
textBox6.AppendText(tReader["email"].ToString() + "\n");
}
tConn.Close();
tReader.Close();
}
catch
{
tConn.Close();
}
}
}
}
//上面这种方法,有点局限性,因为必须得要安装mysql.net的那几个插件
下面这种虽然需要导入引用,但不需要安装插件。
所以,本人常常使用这种方式:
但也需要引用:mysql-connector-net-6.8.3-noinstall里的.dll库文件。
如需要,百度mysql-connector-net-6.8.3-noinstall即可。
主要源码如下:
public void login()
{
string now = DateTime.Now.ToString();//获取系统时间
string user = Form1.xxone;
string hostname = Dns.GetHostName();//获得本机名字
IPHostEntry hostInfo = Dns.GetHostByName(Dns.GetHostName());
string ipss = (hostInfo.AddressList[0].ToString());
for (int i = 0; i < hostInfo.AddressList.Length; i++)
ipss = ipss + " "+hostInfo.AddressList[i];//获得本机
string mystr = "server=mysql地址;User Id=用户名;password=密码;Database=库名";//定义连接字符串
MySqlConnection mycon = new MySqlConnection(mystr);
try
{
mycon.Open();
string tCmd = string.Format("INSERT INTO `cardlose` (`stuNumber`,`ip`,`uptime`,`hostname`,`number`)VALUES ('{0}', '{1}', '{2}','{3}','{4}')", user, ipss, now,hostname,"");
MySqlCommand cmd = new MySqlCommand(tCmd, mycon);
cmd.ExecuteNonQuery();
mycon.Close();
}
catch
{
mycon.Close();
}
}