c#mysqlDb连接在单独的类中

时间:2013-10-10 17:50:54

标签: c# mysql class

我有问题。 问题是我想在项目范围内使用相同的数据库连接。 我认为我需要为它创建一个单独的类。 我想要的是: 我想要像Sqliteconnection组件,但对于MYSQL。 一个处理与mysql数据库连接的类,可以从代码中的任何地方访问。 谷歌搜索这种东西,在这里使用搜索 - 没有运气。 我对c#很新,所以我非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

这是一个为sql server创建数据库连接的类,你必须对Mysql进行适当的更改;

public class SQLServer
{   
    SqlConnection myConnection = null;
    SqlCommand myCommand = null;
    /// <summary>
    /// Connection information should be stored in the appp.conf
    /// Example:
    /// <add name="SQLConnection" connectionString="Data Source=server;Initial Catalog=YourDatabase;
    ///   Integrated Security="True" providerName="System.Data.SqlClient"/>
    /// </summary>
    public SQLServer()
    {
      string myConfig = ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString;
      myConnection = new SqlConnection(myConfig);
      myConnection.Open();
    }

    //Executes sql query and returns datareader     
    public SqlDataReader NewReader(string sSQL)
    {
      myCommand = new SqlCommand(sSQL, myConnection);
      SqlDataReader myReader = myCommand.ExecuteReader();
      return myReader;
    }

    //Execute sql statement and returns nothing usefull for inserts and updates
    public void Execute(string SQL)
    {
      Execute(SQL, false);
    }
 }

使用该课程;

SQLServer myClass = new SQLServer();
SqlDataReader myReader = myClass.NewReader("SQL Syntax");
while (myReader.Read())
{
  MessageBox.Show(myReader["some_field"].ToString())
}

我省略了任何错误处理和关闭连接,请确保这样做以避免出现问题。