我是C#编程的新手,但希望能够访问MySQL数据库(没有用于MS SQL的资金)
但是我有一个问题。我知道您必须具有“ MySQL连接器/ NET”和“ MySQL for Visual Studio”才能开发C#应用程序,但是安装该应用程序的人还需要它们吗?(是否可以随程序释放连接器DLL?)
谢谢
编辑:最终用户还是只是连接器都需要它们?他们还有什么需要的吗?
安装Oracle的MySql.DataNuGet软件包。
using MySql.Data; using MySql.Data.MySqlClient;
namespace Data { public class DBConnection { private DBConnection() { }
private string databaseName = string.Empty;
public string DatabaseName
{
get { return databaseName; }
set { databaseName = value; }
}
public string Password { get; set; }
private MySqlConnection connection = null;
public MySqlConnection Connection
{
get { return connection; }
}
private static DBConnection _instance = null;
public static DBConnection Instance()
{
if (_instance == null)
_instance = new DBConnection();
return _instance;
}
public bool IsConnect()
{
if (Connection == null)
{
if (String.IsNullOrEmpty(databaseName))
return false;
string connstring = string.Format("Server=localhost; database={0}; UID=UserName; password=your password", databaseName);
connection = new MySqlConnection(connstring);
connection.Open();
}
return true;
}
public void Close()
{
connection.Close();
}
}
} 例:
var dbCon = DBConnection.Instance(); dbCon.DatabaseName = "YourDatabase"; if (dbCon.IsConnect()) { //suppose col0 and col1 are defined as VARCHAR in the DB string query = "SELECT col0,col1 FROM YourTable"; var cmd = new MySqlCommand(query, dbCon.Connection); var reader = cmd.ExecuteReader(); while(reader.Read()) { string someStringFromColumnZero = reader.GetString(0); string someStringFromColumnOne = reader.GetString(1); Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne); } dbCon.Close(); } 来源:stack overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。