c#连接Mysql数据库 Connect to mySQL in C#

Instructions:
1) Download and install the connector: url=http://dev.mysql.com/downloads/connector/net/1.0.html
2) Create a test project
3)Next add reference to: MySql.Data
4) Next add "using MySql.Data.MySqlClient;"
 

/// <summary>
    /// Method for connection to a mySQL database. You
    /// need to download the mySQL Connector located at
    /// http://dev.mysql.com/downloads/connector/net/1.0.html]
    ///
    /// NOTE: I am a big supporter of having the connection
    /// stored in the web.config, not inline like this
    /// </summary>
    /// <param name="server"></param>
    private void connectoToMySql(string server)
    {
        //set your connection string.
        //NOTE: I am a big supporter of having the connection
        //stored in the web.config, not inline like this
        string connString = "SERVER=" + server + ";" +
                "DATABASE=mydatabase;" +
                "UID=testuser;" +
                "PASSWORD=testpassword;";
        //create your mySQL connection
        MySqlConnection cnMySQL = new MySqlConnection(connString);
        //create your mySql command object
        MySqlCommand cmdMySQL = cnMySQL.CreateCommand();
        //create your mySQL reeader object
        MySqlDataReader reader;
        //set the command text (query) of the
        //mySQL command object
        cmdMySQL.CommandText = "select * from mycustomers";
        //open the mySQL connection
        cnMySQL.Open();
        //execute the reader, thus retrieving the data
        reader = cmdMySQL.ExecuteReader();
        //while theres data keep reading
        while (reader.Read())
        {
            string thisrow = "";
            for (int i = 0; i < reader.FieldCount; i++)
                thisrow += reader.GetValue(i).ToString() + ",";
            listBox1.Items.Add(thisrow);
        }
        cnMySQL.Close();
    }



上一篇: Asp.net c#当前上下文中不存在名称“Encoding”
下一篇: 常用正则表达式
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: c#
相关日志:
评论: 0 | 引用: 0 | 查看次数: 4146
发表评论
昵 称:
密 码: 游客发言不需要密码.
邮 箱: 邮件地址支持Gravatar头像,邮箱地址不会公开.
网 址: 输入网址便于回访.
内 容:
验证码:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭

 广告位

↑返回顶部↑