使用C#连接到ASPX网站的MYSQL数据库

时间:2012-09-23 19:17:38

标签: c# asp.net mysql database connection

有人可以写一个如何从我的ASPX网站连接到我的数据库的简单示例吗? 我刚开始使用ASP,所以请保持简单。

MysqlDB名称:ASP
类:Database.cs

1 个答案:

答案 0 :(得分:2)

也许这会有所帮助

首先,您需要在此链接中添加一些可以下载的参考:http://dev.mysql.com/downloads/connector/net/

这是代码:

using MySql.Data.MysqlClient;

namespace OwnNameSpace
{
  public class Database
  {
    MySqlConnection connect;
    string connection = "Data Source=localhost;Database=ASP;User ID=(your ID)";
//constructor
public Database()
{
}

  // this if want to select something in your db
  public MySqlDataReader Select(string query)
  {

      connect = new MySqlConnection(connection);
      connect.Close();
      MySqlCommand command = connect.CreateCommand();
      command.CommandText = query;
      connect.Open();
      MySqlDataReader reader;
      return reader = command.ExecuteReader();
  }

  // this if want to insert/delete or update 
  public Boolean Modify(string query)
  {

      connect = new MySqlConnection(connection);
      MySqlCommand command = connect.CreateCommand();
      command.CommandText = query;
      connect.Open();
      try
      {
         command.ExecuteNonQuery();
         return true;
      }
      catch
      {
        return false;
      }

   }



 }
}