本文整理汇总了C#中MySql.Data.MySqlClient.MySqlConnectionStringBuilder.GetConnectionString方法的典型用法代码示例。如果您正苦于以下问题:C# MySqlConnectionStringBuilder.GetConnectionString方法的具体用法?C# MySqlConnectionStringBuilder.GetConnectionString怎么用?C# MySqlConnectionStringBuilder.GetConnectionString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MySql.Data.MySqlClient.MySqlConnectionStringBuilder
的用法示例。
在下文中一共展示了MySqlConnectionStringBuilder.GetConnectionString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: MySQLDatabaseHandler
public MySQLDatabaseHandler(string vHostOrIP, string vDatabaseName, string vUser, string vPassword)
{
MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
builder.Database = vDatabaseName;
builder.UserID = vUser;
builder.Password = vPassword;
builder.Server = vHostOrIP;
string conSTring = builder.GetConnectionString(true);
conn = new MySqlConnection(builder.GetConnectionString(true));
}
示例2: Connect
/// <summary>
/// 链接数据库测试,第一要执行的任务
/// </summary>
/// <param name="config">配置文件</param>
/// <param name="connectionString">链接字符串</param>
/// <returns>是否链接成功</returns>
public bool Connect(ConnectionConfig config, ref string connectionString)
{
MySqlConnectionStringBuilder bui = new MySqlConnectionStringBuilder();
bui.Server = config.Server;
bui.Database = config.Database;
bui.UserID = config.User;
bui.Password = config.Password;
if (config.Port != 3306) bui.Port = config.Port;
connectionString = bui.GetConnectionString(!string.IsNullOrEmpty(config.Password));
using (MySqlConnection con = new MySqlConnection(connectionString))
{
try
{
con.Open();
IsConnect = true;
Config = config;
this._conStr = connectionString;
}
catch
{
IsConnect = false;
return false;
}
}
return true;
}
示例3: MySqlEICData
public MySqlEICData(string server, string dataBase, string userName, string password)
{
MySqlConnectionStringBuilder connStrBuilder = new MySqlConnectionStringBuilder();
connStrBuilder.Server = server;
connStrBuilder.Database = dataBase;
connStrBuilder.UserID = userName;
connStrBuilder.Password = password;
this._dataAdapter = new MySqlEICDataAdapter(connStrBuilder.GetConnectionString(true));
}
示例4: IConnectToMySQL
private static IDbConnection IConnectToMySQL()
{
MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder();
sb.Database = pngIni.Ini["Database.Name"];
sb.Password = pngIni.Ini["Database.Password"];
sb.Server = pngIni.Ini["Database.Host"];
sb.UserID = pngIni.Ini["Database.User"];
MySqlConnection conn = new MySqlConnection(sb.GetConnectionString(true));
try {
conn.Open();
} catch (Exception e) {
throw new pnDbException("Failed to connect to MySQL", e);
}
return conn;
}
示例5: GetPool
public static MySqlPool GetPool(MySqlConnectionStringBuilder settings)
{
string text = settings.GetConnectionString(true);
lock (pools.SyncRoot)
{
MySqlPool pool = (pools[text] as MySqlPool);
if (pool == null)
{
pool = new MySqlPool(settings);
pools.Add(text, pool);
}
else
pool.Settings = settings;
return pool;
}
}
示例6: MySqlUserDataSource
public MySqlUserDataSource()
{
m_logger = LogManager.GetLogger("MySqlUserDataSource");
MySqlConnectionStringBuilder bldr = new MySqlConnectionStringBuilder();
bldr.Server = Settings.Store.Host;
int port = Settings.Store.Port;
bldr.Port = Convert.ToUInt32(port);
bldr.UserID = Settings.Store.User;
bldr.Database = Settings.Store.Database;
bldr.Password = Settings.Store.GetEncryptedSetting("Password");
bool useSsl = Settings.Store.UseSsl;
if (useSsl)
bldr.SslMode = MySqlSslMode.Required;
m_conn = new MySqlConnection(bldr.GetConnectionString(true));
if( m_conn != null ) m_conn.Open();
else throw new Exception("Unable to create connection to database.");
}
示例7: SetConStr
public static void SetConStr()
{
string strjosn = File.ReadAllText("log\\constr.log");
DBModel db = JsonConvert.DeserializeObject<DBModel>(strjosn);
MySqlConnectionStringBuilder msc = new MySqlConnectionStringBuilder();
msc.CharacterSet = "utf8";
msc.Server = db.Server;
msc.Database = db.DataBase;
msc.UserID = db.User;
msc.Password = db.PassWord;
ConStr = msc.GetConnectionString(!string.IsNullOrEmpty(db.PassWord));
if (string.IsNullOrEmpty(db.PassWord))
{
ConStr = string.Format("Server={0};Database={1}; User={2};", db.Server, db.DataBase, db.User);
}
else
{
ConStr = string.Format("Server={0};Database={1}; User={2};Password={3};", db.Server, db.DataBase, db.User, db.PassWord);
}
}
示例8: button1_Click
private void button1_Click(object sender, EventArgs e)
{
MySqlConnectionStringBuilder ConnectionString = new MySqlConnectionStringBuilder(); //Создаем объект строки подклбчения к БД.
//Можем сразу написать строку подключения
//или вбить параметры отдельно. Я вбиваю отдельно
ConnectionString.Server = "127.0.0.1"; //здесь пишем адрес сервера с базой данных.
//Так как наш сервер находтся на этом компьютере
//пишем такой адрес
ConnectionString.Database = "test"; //Имя базы к кторой подключаемся
ConnectionString.UserID = textBox1.Text; //Имя пользователя. Здесь нуно будетм указать свое имя
ConnectionString.Password = textBox2.Text;//Пароль ползователя
Connection = new MySqlConnection(ConnectionString.GetConnectionString(true)); //Создаем объект подключения к БД. В касестве ппраметра
//конструктору передаем строку подключение с методом GetConnectionString(true)
//True означет что мы преедаем строку подключения вместе с паролем
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button1.Enabled = false;
}
示例9: Configure
public override void Configure(Container container)
{
Plugins.Add(new SwaggerFeature());
{
var reqlog = new RequestLogsFeature();
Plugins.Add(reqlog);
}
{
var cfgfile = new IniFile("stksto.ini", null);
var dbhost = cfgfile.ReadValue("db", "host");
var dbport = int.Parse(cfgfile.ReadValue("db", "port"));
var dbuser = cfgfile.ReadValue("db", "user");
var dbpwd = cfgfile.ReadValue("db", "pwd");
var dbname = cfgfile.ReadValue("db", "db");
OrmLiteConfig.DialectProvider = MySqlDialect.Provider;
//先手工写,以后放到配置文件里去
var blder = new MySqlConnectionStringBuilder
{
Server = dbhost,
Port = (uint)dbport,
UserID = dbuser,
Password = dbpwd,
Database = dbname,
OldGuids = true,
CharacterSet = "utf8",
Pooling = true
};
string ConnStr = blder.GetConnectionString(true);
container.Register<IDbConnectionFactory>(c =>
{
return new OrmLiteConnectionFactory(ConnStr, MySqlDialect.Provider);
});
}
HostConfig conf = new HostConfig();
//conf.EnableFeatures = Feature.All.Remove(Feature.Csv | Feature.Soap | Feature.Jsv | Feature.Markdown);
conf.DebugMode = true;
SetConfig(conf);
}
示例10: BuildConnectionString
private string BuildConnectionString()
{
uint port = 0;
try
{
port = Convert.ToUInt32(this.portTB.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid port number.");
return null;
}
MySqlConnectionStringBuilder bldr = new MySqlConnectionStringBuilder();
bldr.Server = this.hostTB.Text.Trim();
bldr.Port = port;
bldr.UserID = this.userTB.Text.Trim();
bldr.Database = this.dbTB.Text.Trim();
bldr.Password = this.passwdTB.Text;
return bldr.GetConnectionString(true);
}
示例11: BuildConnectionString
private static string BuildConnectionString()
{
uint port = 0;
try
{
port = Convert.ToUInt32((String)Settings.Store.Port);
}
catch (FormatException e)
{
throw new Exception("Invalid port number.", e);
}
MySqlConnectionStringBuilder bldr = new MySqlConnectionStringBuilder();
bldr.Server = Settings.Store.Host;
bldr.Port = port;
bldr.UserID = Settings.Store.User;
bldr.Database = Settings.Store.Database;
bldr.Password = Settings.Store.GetEncryptedSetting("Password");
//m_logger.DebugFormat("Connecting to {0}:{1} as {2}, database: {3}",
// bldr.Server, bldr.Port, bldr.UserID, bldr.Database);
return bldr.GetConnectionString(true);
}
示例12: IsOpen
/// <summary>
/// 判断数据库是否连接成功
/// </summary>
/// <param name="db"></param>
/// <returns></returns>
public static bool IsOpen(DBModel db)
{
string str;
//现这个连接字符串测试
MySqlConnectionStringBuilder msc = new MySqlConnectionStringBuilder();
msc.CharacterSet = "utf8";
msc.Server = db.Server;
msc.Database = db.DataBase;
msc.UserID = db.User;
msc.Password = db.PassWord;
str = msc.GetConnectionString(!string.IsNullOrEmpty(db.PassWord));
using (MySqlConnection con = new MySqlConnection(str))
{
try
{
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
//连接成功
//生成连接字符串
ConStr = str;
//写入到日记中
string dbjson = JsonConvert.SerializeObject(db);
if (!Directory.Exists("log")) Directory.CreateDirectory("log");
File.WriteAllText("log\\constr.log", dbjson, Encoding.UTF8);
return true;
}
return false;
}
catch (Exception)
{
return false;
}
}
}
示例13: reopenDatabase
private void reopenDatabase()
{
MySqlConnectionStringBuilder mycsb = new MySqlConnectionStringBuilder
{
Password = textBox3.Text,
Port = (uint) numericUpDown1.Value,
Server = textBox1.Text,
UserID = textBox2.Text
};
if (_conn != null)
if (_conn.State == ConnectionState.Open)
_conn.Close();
_conn = new MySqlConnection(mycsb.GetConnectionString(true));
_conn.Open();
}
示例14: GetUserEntry
private UserEntry GetUserEntry(string user)
{
m_logger.Debug("GetUserEntry");
MySqlConnectionStringBuilder bldr = new MySqlConnectionStringBuilder();
bldr.Server = Settings.Store.Host;
int port = Settings.Store.Port;
bldr.Port = Convert.ToUInt32(port);
bldr.UserID = Settings.Store.User;
bldr.Database = Settings.Store.Database;
bldr.Password = Settings.Store.GetEncryptedSetting("Password");
bool useSsl = Settings.Store.UseSsl;
if (useSsl)
bldr.SslMode = MySqlSslMode.Required;
string tableName = Settings.Store.Table;
try
{
using (MySqlConnection conn = new MySqlConnection(bldr.GetConnectionString(true)))
{
conn.Open();
string query = string.Format("SELECT user, hash_method, password " +
"FROM {0} WHERE [email protected]", tableName);
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@user", user);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
rdr.Read();
PasswordHashAlgorithm hashAlg;
string uname = rdr[0].ToString();
string hash = rdr[2].ToString();
switch (rdr[1].ToString())
{
case "NONE":
hashAlg = PasswordHashAlgorithm.NONE;
break;
case "MD5":
hashAlg = PasswordHashAlgorithm.MD5;
break;
case "SMD5":
hashAlg = PasswordHashAlgorithm.SMD5;
break;
case "SHA1":
hashAlg = PasswordHashAlgorithm.SHA1;
break;
case "SSHA1":
hashAlg = PasswordHashAlgorithm.SSHA1;
break;
case "SHA256":
hashAlg = PasswordHashAlgorithm.SHA256;
break;
case "SSHA256":
hashAlg = PasswordHashAlgorithm.SSHA256;
break;
case "SHA512":
hashAlg = PasswordHashAlgorithm.SHA512;
break;
case "SSHA512":
hashAlg = PasswordHashAlgorithm.SSHA512;
break;
case "SHA384":
hashAlg = PasswordHashAlgorithm.SHA384;
break;
case "SSHA384":
hashAlg = PasswordHashAlgorithm.SSHA384;
break;
default:
m_logger.ErrorFormat("Unrecognized hash algorithm: {0}", rdr[1].ToString());
return null;
}
rdr.Close();
return new UserEntry(uname, hashAlg, hash);
}
else
{
return null;
}
}
}
catch (MySqlException ex)
{
if (ex.Number == 1042)
m_logger.ErrorFormat("Unable to connect to host: {0}", Settings.Store.Host);
else
m_logger.Error(ex.ToString());
// Return null causes failed auth.
return null;
}
}
示例15: RunCreation
public static void RunCreation(CreationScript script, string server, string dbname, string login, string password)
{
if (script == null)
script = Scripts.First ();
string connStr, host;
uint port = 3306;
string[] uriSplit = server.Split (new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries);
host = uriSplit [0];
if (uriSplit.Length > 1) {
uint.TryParse(uriSplit [1], out port);
}
var conStrBuilder = new MySqlConnectionStringBuilder();
conStrBuilder.Server = host;
conStrBuilder.Port = port;
conStrBuilder.UserID = login;
conStrBuilder.Password = password;
connStr = conStrBuilder.GetConnectionString(true);
var connectionDB = new MySqlConnection (connStr);
try {
logger.Info ("Connecting to MySQL...");
connectionDB.Open();
} catch (MySqlException ex) {
logger.Info ("Строка соединения: {0}", connStr);
logger.Error (ex, "Ошибка подключения к серверу.");
if (ex.Number == 1045 || ex.Number == 0)
MessageDialogWorks.RunErrorDialog ("Доступ запрещен.\nПроверьте логин и пароль.");
else if (ex.Number == 1042)
MessageDialogWorks.RunErrorDialog ("Не удалось подключиться к серверу БД.");
else
MessageDialogWorks.RunErrorDialog ("Ошибка соединения с базой данных.");
connectionDB.Close ();
return;
}
logger.Info ("Проверяем существует ли уже база.");
var sql = "SHOW DATABASES;";
var cmd = new MySqlCommand (sql, connectionDB);
bool needDropBase = false;
using (var rdr = cmd.ExecuteReader ())
{
while (rdr.Read ()) {
if (rdr [0].ToString () == dbname) {
if (MessageDialogWorks.RunQuestionDialog ("База с именем `{0}` уже существует на сервере. Удалить существующую базу перед соданием новой?", dbname)) {
needDropBase = true;
break;
} else
return;
}
}
}
logger.Info ("Создаем новую базу.");
progressDlg = new CreatorProgress ();
progressDlg.OperationText = "Получаем скрипт создания базы";
progressDlg.Show ();
string sqlScript;
using(Stream stream = System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream(script.Resource))
{
if(stream == null)
throw new InvalidOperationException( String.Format("Ресурс {0} со скриптом не найден.", script.Resource));
StreamReader reader = new StreamReader(stream);
sqlScript = reader.ReadToEnd();
}
int predictedCount = Regex.Matches(sqlScript, ";").Count;
logger.Debug ("Предполагаем наличие {0} команд в скрипте.", predictedCount);
progressDlg.OperationText = String.Format ("Создаем базу <{0}>", dbname);
progressDlg.OperationPartCount = predictedCount + (needDropBase ? 2 : 1);
progressDlg.OperationCurPart = 0;
if(needDropBase)
{
logger.Info ("Удаляем существующую базу {0}.", dbname);
progressDlg.OperationText = String.Format ("Удаляем существующую базу {0}", dbname);
cmd.CommandText = String.Format ("DROP DATABASE `{0}`", dbname);
cmd.ExecuteNonQuery ();
progressDlg.OperationCurPart++;
}
cmd.CommandText = String.Format ("CREATE SCHEMA `{0}` DEFAULT CHARACTER SET utf8 ;", dbname);
cmd.ExecuteNonQuery ();
cmd.CommandText = String.Format ("USE `{0}` ;", dbname);
cmd.ExecuteNonQuery ();
progressDlg.OperationText = String.Format ("Создаем таблицы в <{0}>", dbname);
progressDlg.OperationCurPart++;
var myscript = new MySqlScript(connectionDB, sqlScript);
myscript.StatementExecuted += Myscript_StatementExecuted;;
//.........这里部分代码省略.........