1. 程式人生 > >IBatis.NET連線MySQL資料庫配置筆記

IBatis.NET連線MySQL資料庫配置筆記

Software Version:IBatis.NET 1.6.2.0

MySQL :5.5.10

mysql-connector-net:6.4.3

visual studio 2010

-----------------------------------------------------------------------------------------------

以下是具體事例步驟:

1、將SqlMapConfig.xsd、SqlMap.xsd、provider.xsd三個檔案Copy到“D:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas”目錄中,以便vs能夠識別IBatis的一些屬性

ps:“D:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas”目錄是VS的安裝目錄,請根據自己的目錄自行解決。

2、新建一個Project,筆者新建的是WinForm專案。

3、將“Ibatis.DataMapper.1.6.2.bin”目錄下的IBatisNet.DataMapper.dll、IBatisNet.Common.dll兩個檔案copy到專案中。

並且新增到引用裡面。

ps:以上兩個dll檔案是否必須新增到專案中有待論證。

4、將“Ibatis.DataMapper.1.6.2.bin”目錄下的providers.config複製到專案中,並且把除MySql以外的其他provider的enabled屬性設定為false,MySql的enabled屬性設定為true:

<provider
    name="MySql"
    description="MySQL, MySQL provider 6.4.3.0"
    enabled="true"
    assemblyName="MySql.Data, Version=6.4.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionClass="MySql.Data.MySqlClient.MySqlConnection"
    commandClass="MySql.Data.MySqlClient.MySqlCommand"
    parameterClass="MySql.Data.MySqlClient.MySqlParameter"
    parameterDbTypeClass="MySql.Data.MySqlClient.MySqlDbType"
    parameterDbTypeProperty="MySqlDbType"
    dataAdapterClass="MySql.Data.MySqlClient.MySqlDataAdapter"
    commandBuilderClass="MySql.Data.MySqlClient.MySqlCommandBuilder"
    usePositionalParameters="false"
    useParameterPrefixInSql="true"
    useParameterPrefixInParameter="true"
    parameterPrefix="?"
    allowMARS="false"   
  />

ps:注意version的版本號匹配。

5、“Ibatis.DataMapper.1.6.2.bin”目錄下的sample.SqlMap.config檔案複製到專案中,改名為SqlMap.config(不是必須的)。內容如下:

<?xml version="1.0" encoding="utf-8"?>
<sqlMapConfig
  xmlns="http://ibatis.apache.org/dataMapper"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <settings>
        <setting useStatementNamespaces="false"/>
        <setting cacheModelsEnabled="true"/>
    </settings>

    <providers resource="..\..\providers.config"/>

    <database>
        <provider name="MySql"/>
        <dataSource name="mybatisSource"
                   connectionString="Host=localhost;
                   UserName=root;
                   Password=123;
                   Database=mybatis;
                   Port=3306;" />
    </database>

    <sqlMaps>
        <sqlMap resource="..\..\User.xml"/>
    </sqlMaps>

</sqlMapConfig>

6、新增Mapper檔案User.xml

<?xml version="1.0" encoding="utf-8" ?>
<sqlMap namespace="User"
        xmlns="http://ibatis.apache.org/mapping"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <alias>
        <typeAlias alias="User" type="MybatisTest.User,MybatisTest" />
    </alias>

    <statements>
        <insert id="InsertUser" parameterClass="User">
            INSERT INTO user
            (id, name)
            VALUES
            (#Id#,#Name#)
        </insert>

        <select id="SelectUser" parameterClass="int" resultMap="select_user_result">
            SELECT
            id
            ,name
            FROM user
            WHERE
            id = #value#
        </select>

        <select id="SelectUserList" parameterClass="int" resultMap="select_user_result">
            SELECT
            id
            ,name
            FROM user
        </select>

        <update id="update_user" parameterClass="User">
            UPDATE user set
            name = #Name#
            WHERE
            id = #Id#
        </update>
       
    </statements>
    <resultMaps>
        <resultMap id="select_user_result" class="User">
            <result property="Id" column="id"/>
            <result property="Name" column="name"/>
        </resultMap>
    </resultMaps>
</sqlMap>

7、實現程式:

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 System.Configuration;
using IBatisNet.DataMapper.Configuration;
using IBatisNet.DataMapper;

namespace MybatisTest
{
    public partial class Form1 : Form
    {
        private static ISqlMapper mapper;
        public Form1()
        {
            InitializeComponent();
            InitMapper();
        }

        public void InitMapper()
        {
            DomSqlMapBuilder builder = new DomSqlMapBuilder();
            mapper = builder.Configure("..\\..\\SqlMap.config");
        }

        private void InsertButton_Click(object sender, EventArgs e)
        {
            string id = this.IDTextBox.Text.Equals("") ? "0" : this.IDTextBox.Text;
            User user = new User()
            {
                Id = int.Parse(id),
                Name = this.NameTextBox.Text,
            };
            try
            {
                mapper.Insert("InsertUser", user);
                MessageBox.Show(this, "Insert success!", "Tips"
                    , MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error"
                    , MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void SelectButton_Click(object sender, EventArgs e)
        {
            if (this.IDTextBox.Text.Equals("") == true)
            {
                MessageBox.Show(this, "The id is null,please input a number!", "Tips"
                , MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                int id = int.Parse(this.IDTextBox.Text);
                User user = mapper.QueryForObject("SelectUser", id) as User;

                this.ResultLabel.Text = "Result is :\nid:" + user.Id.ToString()
                    + "\nname:" + user.Name;
            }
        }

        private void SelectListButton_Click(object sender, EventArgs e)
        {
            List<User> users = mapper.QueryForList<User>("SelectUserList", null) as List<User>;
            this.ResultLabel.Text = "Result is :\n";
            foreach (User user in users)
            {
                this.ResultLabel.Text += "id:" + user.Id.ToString()
                    + "\nname:" + user.Name+"\n";
            }
        }

        private void UpdateButton_Click(object sender, EventArgs e)
        {
            string id = this.IDTextBox.Text.Equals("") ? "0" : this.IDTextBox.Text;
            User user = new User()
            {
                Id = int.Parse(id),
                Name = this.NameTextBox.Text,
            };

            try
            {
                int result = mapper.Update("update_user", user);
                if (result > 0)
                {
                    MessageBox.Show(this, "Update success!", "Tips"
                    , MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show(this, "Update failed!", "Tips"
                    , MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error"
                    , MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

介面設計如下:



ps:MySQL中需要手動建立資料庫mybatis,以及表user