Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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()
- {
- bool result = true;
- if (Connection == null)
- {
- if (String.IsNullOrEmpty(databaseName))
- result = false;
- string connstring = string.Format("Server=localhost; database={0}; UID=UserName; password=your password", databaseName);
- connection = new MySqlConnection(connstring);
- connection.Open();
- result = true;
- }
- return result;
- }
- 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);
- }
- }
- PM> Install-Package MySql.Data
- private void Initialize()
- {
- server = "localhost";
- database = "connectcsharptomysql";
- uid = "username";
- password = "password";
- string connectionString;
- connectionString = "SERVER=" + server + ";" + "DATABASE=" +
- database + ";" + "U`enter code here`ID=" + uid + ";" + "PASSWORD=" + password + ";";
- connection = new MySqlConnection(connectionString);
- }
- protected readonly static string Server = "server";
- protected readonly static string UserName = "username";
- protected readonly static string Password = "password";
- protected readonly static string Database = "database";
- protected readonly static string Port = "port";
- public readonly string config = string.Format("Server = {0}; Port = {1}; Database = {2}; Uid = {3}; Pwd = {4}; pooling = true; Allow Zero Datetime = False; Min Pool Size = 0; Max Pool Size = 200; ", Server, Port, Database, UserName, Password);
- using (var con = new MySqlConnection { ConnectionString = config })
- {
- con.Open();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement