十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
c#连接MySql数据库的方法
创新互联专注为客户提供全方位的互联网综合服务,包含不限于成都网站制作、做网站、巩留网络推广、小程序开发、巩留网络营销、巩留企业策划、巩留品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联为所有大学生创业者提供巩留建站搭建服务,24小时服务热线:028-86922220,官方网址:www.cdcxhl.com
一、用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.TexttReader["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();
}
}
}
Where查询条件,on内外连接时候用,as作为别名,in查询某值是否在某条件里
为了使用简单,我做了一个简单的包装类(包含一个数据结构):
package com.easily.ds
{
public class DataBaseData
{
public var host:String;
public var port:int;
public var username:String;
public var password:String;
public var database:String;
}
}
package com.easily.util
{
import com.easily.ds.DataBaseData;
import com.maclema.mysql.Connection;
import com.maclema.mysql.Field;
import com.maclema.mysql.MySqlResponse;
import com.maclema.mysql.MySqlToken;
import com.maclema.mysql.ResultSet;
import com.maclema.mysql.Statement;
import flash.events.Event;
import flash.events.EventDispatcher;
import mx.rpc.AsyncResponder;
/**
* @author Easily
*/
public class DataBase extends EventDispatcher
{
private var mDataBase:DataBaseData;
private var mConnection:Connection;
public function DataBase(database:DataBaseData)
{
mDataBase = database;
}
public function connect():void
{
mConnection = new Connection(mDataBase.host, mDataBase.port,
mDataBase.username, mDataBase.password, mDataBase.database);
mConnection.addEventListener(Event.CONNECT, onConnected);
mConnection.connect();
function onConnected(event:Event):void
{
mConnection.removeEventListener(Event.CONNECT, onConnected);
dispatchEvent(event);
}
}
public function disconnect():void
{
mConnection.disconnect();
}
public function select(sql:String, completeHandler:Function, errorHandler:Function = null):void
{
var st:Statement = mConnection.createStatement();
var token:MySqlToken = st.executeQuery(sql);
var responder:AsyncResponder = new AsyncResponder(resultHandler, faultHandler, token);
token.addResponder(responder);
function resultHandler(result:Object/*ResultSet*/, token:Object/*MySqlToken*/):void
{
var data:Array = [];
if (result is ResultSet)
{
var fieldList:Array = result.getColumns();
while (result.next())
{
var item:Object = {};
for each (var field:Field in fieldList)
{
item[field.getName()] = result.getString(field.getName());
}
data.push(item);
}
}
completeHandler(data);
}
function faultHandler(info:Object, token:Object):void
{
if (errorHandler == null) return;
errorHandler();
}
}
public function insert(sql:String, completeHandler:Function, errorHandler:Function = null):void
{
var st:Statement = mConnection.createStatement();
var token:MySqlToken = st.executeQuery(sql);
var responder:AsyncResponder = new AsyncResponder(resultHandler, faultHandler, token);
token.addResponder(responder);
function resultHandler(result:Object/*MySqlResponse*/, token:Object/*MySqlToken*/):void
{
completeHandler(result.insertID);
}
function faultHandler(info:Object, token:Object):void
{
if (errorHandler == null) return;
errorHandler();
}
}
public function remove(sql:String, completeHandler:Function, errorHandler:Function = null):void
{
var st:Statement = mConnection.createStatement();
var token:MySqlToken = st.executeQuery(sql);
var responder:AsyncResponder = new AsyncResponder(resultHandler, faultHandler, token);
token.addResponder(responder);
function resultHandler(result:Object/*MySqlResponse*/, token:Object/*MySqlToken*/):void
{
completeHandler();
}
function faultHandler(info:Object, token:Object):void
{
if (errorHandler == null) return;
errorHandler();
}
}
}
}
其中有3个方法,select,insert,remove,分别对应了SQL语句中的select,insert,delete
用法很简单,先连接:
var databaseData:DataBaseData = new DataBaseData();
databaseData.host = "127.0.0.1";
databaseData.database = "game";
databaseData.password = "123456";
databaseData.port = 3306;
databaseData.username = "root";
var dataBase:DataBase = new DataBase(databaseData);
dataBase.addEventListener(Event.CONNECT, onConnected);
dataBase.connect();
function onConnected(event:Event):void
{
dataBase.removeEventListener(Event.CONNECT, onConnected);
dispatchEvent(new Event(Event.COMPLETE));
}
如果不需要用了可以先断开连接:
dataBase.disconnect();
下面是select语句:
var sql:String = "select id,name from `npc`";
dataBase.select(sql, endQuery);
function endQuery(data:Array):void
{
var npcList:Array= [];
for each (var item:Object in data)
{
var npc:Object = {id:item.id, name:item.name};
npcList.push(npc);
}
}
insert语句用法会返回一个insertID,也就是插入的那条数据的ID。
1.打开IDEA,新建一个Web项目,右键点击新建的项目名,选择创建文件目录(Directory),一般properties文件夹命名应为resoures。
2.右键点击新建的resources文件夹,弹出的窗口里选择Mark Dictory as Resources Root将文件夹定义为配置文件。
3.也可以通过Ctrl+shift+alt+s组合件打开Project Structure面板将需要的文件夹声明为配置文件类型。
(选择文件夹,再点击Mark as:栏里的功能项,就能将文件夹声明为相应的类型)
最后点击OK 完成。
4.右键点击声明为resources类型的文件夹选择Resource Bundle,就能创架一个properties文件了。
5.mysql 的properties配置文件是以键值对形式存读取的,一个对象占用一行,行末不能添加分号。
6.配置文件的使用。
7.以上就是IDEA使用properties配置文件进行mysql数据库连接的方法。