c#連接MySql數(shù)據(jù)庫(kù)的方法
創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于成都網(wǎng)站制作、做網(wǎng)站、鞏留網(wǎng)絡(luò)推廣、小程序開(kāi)發(fā)、鞏留網(wǎng)絡(luò)營(yíng)銷、鞏留企業(yè)策劃、鞏留品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運(yùn)營(yíng)等,從售前售中售后,我們都將竭誠(chéng)為您服務(wù),您的肯定,是我們最大的嘉獎(jiǎng);創(chuàng)新互聯(lián)為所有大學(xué)生創(chuàng)業(yè)者提供鞏留建站搭建服務(wù),24小時(shí)服務(wù)熱線:028-86922220,官方網(wǎng)址:www.cdcxhl.com
一、用MySQLDriverCS連接MySQL數(shù)據(jù)庫(kù)。
先下載和安裝MySQLDriverCS,在安裝文件夾下面找到MySQLDriver.dll,然后將MySQLDriver.dll添加引用到項(xiàng)目中。
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(); //打開(kāi)連接
MySQLCommand cmd4 = new MySQLCommand("set names gb2312", tConn);
cmd4.ExecuteNonQuery();
string tCmd = "select ID,Name,PassWord from managers"; //命令語(yǔ)句
MySQLCommand cmd = new MySQLCommand(tCmd,tConn); //在定義的tConn對(duì)象上執(zhí)行查詢命令
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();//重要!要及時(shí)關(guān)閉
tReader.Close();
}
catch
{
tConn.Close();
}
}
}
}
二、通過(guò)ODBC訪問(wèn)mysql數(shù)據(jù)庫(kù):
1. 安裝Microsoft ODBC.net;
2. 安裝MDAC 2.7或者更高版本;
3. 安裝MySQL的ODBC驅(qū)動(dòng)程序;
4. 管理工具 - 數(shù)據(jù)源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好像沒(méi)有這個(gè)命名空間,在c#2008下測(cè)試自動(dòng)生成的
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);
//處理異常:插入重復(fù)記錄有異常
try{
cmd.ExecuteNonQuery();
}
catch(Exception ex){
Console.WriteLine("record duplicate.");
}finally{
cmd.Dispose();
}
//***********************用read方法讀數(shù)據(jù)到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控件顯示數(shù)據(jù)表**************************
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內(nèi)外連接時(shí)候用,as作為別名,in查詢某值是否在某條件里
為了使用簡(jiǎn)單,我做了一個(gè)簡(jiǎn)單的包裝類(包含一個(gè)數(shù)據(jù)結(jié)構(gòu)):
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個(gè)方法,select,insert,remove,分別對(duì)應(yīng)了SQL語(yǔ)句中的select,insert,delete
用法很簡(jiǎn)單,先連接:
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));
}
如果不需要用了可以先斷開(kāi)連接:
dataBase.disconnect();
下面是select語(yǔ)句:
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語(yǔ)句用法會(huì)返回一個(gè)insertID,也就是插入的那條數(shù)據(jù)的ID。
1.打開(kāi)IDEA,新建一個(gè)Web項(xiàng)目,右鍵點(diǎn)擊新建的項(xiàng)目名,選擇創(chuàng)建文件目錄(Directory),一般properties文件夾命名應(yīng)為resoures。
2.右鍵點(diǎn)擊新建的resources文件夾,彈出的窗口里選擇Mark Dictory as Resources Root將文件夾定義為配置文件。
3.也可以通過(guò)Ctrl+shift+alt+s組合件打開(kāi)Project Structure面板將需要的文件夾聲明為配置文件類型。
(選擇文件夾,再點(diǎn)擊Mark as:欄里的功能項(xiàng),就能將文件夾聲明為相應(yīng)的類型)
最后點(diǎn)擊OK 完成。
4.右鍵點(diǎn)擊聲明為resources類型的文件夾選擇Resource Bundle,就能創(chuàng)架一個(gè)properties文件了。
5.mysql 的properties配置文件是以鍵值對(duì)形式存讀取的,一個(gè)對(duì)象占用一行,行末不能添加分號(hào)。
6.配置文件的使用。
7.以上就是IDEA使用properties配置文件進(jìn)行mysql數(shù)據(jù)庫(kù)連接的方法。