本文整理汇总了C#中System.Data.SqlClient.SqlConnectionStringBuilder类的典型用法代码示例。如果您正苦于以下问题:C# SqlConnectionStringBuilder类的具体用法?C# SqlConnectionStringBuilder怎么用?C# SqlConnectionStringBuilder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SqlConnectionStringBuilder类属于System.Data.SqlClient命名空间,在下文中一共展示了SqlConnectionStringBuilder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CheckConnectionString
public override bool CheckConnectionString(string connectionString)
{
try
{
var builder = new SqlConnectionStringBuilder(connectionString);
if (File.Exists(builder.DataSource) == false)
{
var containingFolder = builder.DataSource.Substring(0, builder.DataSource.LastIndexOf("\\"));
if (Directory.Exists(containingFolder) == false)
{
GenericUtils.CreateFolderStructure(containingFolder);
}
var engine = new SqlCeEngine(connectionString);
engine.CreateDatabase();
}
}
catch (Exception ex) { Console.WriteLine("Unable to create SQL CE database automatically. The database should be created manually. Error Details : " + ex.Message); }
var connectionCretead = CreateConnection(null, connectionString);
if (connectionCretead != null && connectionCretead.State == System.Data.ConnectionState.Open)
{
connectionCretead.Close();
return true;
}
return false;
}
示例2: ParseDalConfigXml
public static DalConfig ParseDalConfigXml(string dalConfigXml)
{
try
{
var ser = new DataContractSerializer(typeof (config.models.old.DalConfig));
var config =
(config.models.old.DalConfig) ser.ReadObject(XmlReader.Create(new StringReader(dalConfigXml)));
// now try to read and parse the the connection string
var connString =
ConfigurationManager.ConnectionStrings[config.ApplicationConnectionString]?.ConnectionString;
var csb = new SqlConnectionStringBuilder(connString);
return new DalConfig()
{
DesignerConnection = new DesignerConnection()
{
Authentication =
((config.DesignerConnection?.Authentication ?? new SimpleDataAccessLayer.Common.config.models.old.WindowsAuthentication()) is
SimpleDataAccessLayer.Common.config.models.old.WindowsAuthentication)
? new config.models.Authentication { AuthenticationType = AuthenticationType.WindowsAuthentication}
: new config.models.Authentication
{
AuthenticationType = AuthenticationType.SqlAuthentication,
SavePassword = true,
UserName =
((config.models.old.SqlAuthentication) config.DesignerConnection?.Authentication)
?.UserName,
Password =
((config.models.old.SqlAuthentication) config.DesignerConnection?.Authentication)
?.Password
},
DatabaseName = csb.InitialCatalog,
ServerName = csb.DataSource
},
RuntimeConnectionStringName = config.ApplicationConnectionString,
Namespace = config.Namespace,
Enums = config.Enums?.Select(e => new SimpleDataAccessLayer.Common.config.models.Enum()
{
Schema = e.Schema,
Alias = e.Alias,
ValueColumn = e.ValueColumn,
KeyColumn = e.KeyColumn,
TableName = e.TableName
}).ToList(),
Procedures = config.Procedures?.Select(p => new Procedure()
{
Alias = p.Alias,
Schema = p.Schema,
ProcedureName = p.ProcedureName
}).ToList()
};
}
catch (Exception e)
{
throw new DalConfigXmlConverterException("Failed to parse DalConfig XML", e);
}
}
示例3: FromConnectionString
public static DatabaseModel FromConnectionString(string ConnectionString)
{
var result = new DatabaseModel();
try
{
var csb = new SqlConnectionStringBuilder(ConnectionString);
if (!string.IsNullOrEmpty(csb.DataSource))
result.Server = csb.DataSource;
if (!string.IsNullOrEmpty(csb.InitialCatalog))
result.DatabaseName = csb.InitialCatalog;
if (csb.IntegratedSecurity)
{
result.AuthMethod = "SSPI";
}
else
{
result.AuthMethod = "SQL";
result.Auth_SQL_Username = csb.UserID;
result.Auth_SQL_Password = csb.Password;
}
}
catch (Exception)
{
// Ignore Parsing errors
}
return result;
}
示例4: GetDatabaseName
public string GetDatabaseName(string oldName, SqlConnectionStringBuilder connectionString, ref int postfix)
{
int postFix = postfix;
string newName = oldName;
while (true)
{
if (SqlServerManager.Instance.DatabaseExists(newName, connectionString))
{
newName = oldName;
postFix++;
newName += "_" + postFix.ToString();
}
else
{
if (postFix != -1)
{
postfix = postFix;
}
return newName;
}
}
throw new Exception("Can't get a new DB name. (SIM.Pipelines.Import.ImportRestoreDatabases)");
}
示例5: CreateDatabase
public void CreateDatabase()
{
var connectoinStringBuilder = new SqlConnectionStringBuilder(ConnectionString);
string dbName = connectoinStringBuilder.InitialCatalog;
connectoinStringBuilder.InitialCatalog = string.Empty;
using (var connection = new SqlConnection(connectoinStringBuilder.ToString()))
{
try
{
var serverConnection = new ServerConnection(connection);
var server = new Microsoft.SqlServer.Management.Smo.Server(serverConnection);
var db = new Database(server, dbName);
db.Create();
}
catch (Exception e)
{
throw new Exception(string.Format("Ошибка при создании БД - {0}", e));
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
}
示例6: ParallelBlock
/// <summary>
/// Initializes parallel block during the call to <see cref="Parallel_Declare"/> stored procedure
/// </summary>
/// <param name="name"></param>
public ParallelBlock(SqlString name)
{
string dbName = null;
_startedThreads = new List<string>();
_name = name.IsNull ? string.Empty : name.Value;
//let's get current server name
SqlConnectionStringBuilder connStrBuilder = new SqlConnectionStringBuilder();
connStrBuilder.ContextConnection = true;
using (SqlConnection conn = new SqlConnection(connStrBuilder.ConnectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT DB_NAME()";
cmd.CommandType = CommandType.Text;
dbName = (string)cmd.ExecuteScalar();
}
}
//build connection string, which will be used to execute sql in threads
connStrBuilder = new SqlConnectionStringBuilder();
connStrBuilder.DataSource = "(local)";
connStrBuilder.InitialCatalog = dbName;
connStrBuilder.IntegratedSecurity = true;
connStrBuilder.MultipleActiveResultSets = false;
connStrBuilder.Pooling = true;
connStrBuilder.MaxPoolSize = 30;
connStrBuilder.ConnectTimeout = 30;
//Enlisting will be done when connecting to server if transaction is enabled
connStrBuilder.Enlist = false;
_connectionString = connStrBuilder.ConnectionString;
_threads = new List<ThreadSql>();
}
示例7: GetDatabaseSpecificConnectionString
protected string GetDatabaseSpecificConnectionString(Row row)
{
var builder = new SqlConnectionStringBuilder(_connectionString) {
InitialCatalog = row["database"].ToString()
};
return builder.ConnectionString;
}
示例8: PurgeDb
public static void PurgeDb(Seed seed)
{
ConnectionProfile cp = new ConnectionProfile();
SqlConnectionStringBuilder conn_orig = new SqlConnectionStringBuilder(cp.ConnectionString);
SqlConnectionStringBuilder conn = new SqlConnectionStringBuilder(cp.ConnectionString) { ConnectTimeout = 5, InitialCatalog = "master" }; // you can add other parameters.
using (SqlConnection cnn = new SqlConnection(conn.ConnectionString))
{
cnn.Open();
using (SqlCommand dbCreate = new SqlCommand())
{
dbCreate.CommandText = string.Format(@"IF db_id('{0}') IS NULL CREATE DATABASE [{0}]", conn_orig.InitialCatalog);
dbCreate.Connection = cnn;
try
{
dbCreate.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(string.Format("create database [{0}] FAILED with {1}", conn_orig.InitialCatalog, ex.Message ));
}
}
}
seed.PurgeDb();
}
示例9: CreateProvider
/// <inheritdoc/>
public IConnectionProvider CreateProvider(
IDictionary<string, string> options) {
string connection_string;
if (options.TryGetValue(kConnectionStringOption, out connection_string)) {
return new SqlConnectionProvider(connection_string);
}
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = GetOption(kServerOption, options);
// We try to get the user name information using the "login" key for
// backward compatibility.
string user_id;
if (!options.TryGetValue(kLoginOption, out user_id)) {
user_id = GetOption(kUserNameOption, options);
}
builder.UserID = user_id;
builder.Password = GetOption(kPasswordOption, options);
string catalog;
if (options.TryGetValue(kInitialCatalogOption, out catalog)) {
builder.InitialCatalog = catalog;
}
return new SqlConnectionProvider(builder.ConnectionString);
}
示例10: Init
public override bool Init(IDictionary<string, string> jobArgsDictionary)
{
try
{
var instrumentationKey = JobConfigurationManager.TryGetArgument(jobArgsDictionary, JobArgumentNames.InstrumentationKey);
ApplicationInsights.Initialize(instrumentationKey);
var azureCdnPlatform = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.AzureCdnPlatform);
var cloudStorageAccountConnectionString = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.AzureCdnCloudStorageAccount);
var databaseConnectionString = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.StatisticsDatabase);
_cloudStorageAccount = ValidateAzureCloudStorageAccount(cloudStorageAccountConnectionString);
_targetDatabase = new SqlConnectionStringBuilder(databaseConnectionString);
_azureCdnAccountNumber = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.AzureCdnAccountNumber);
_azureCdnPlatform = ValidateAzureCdnPlatform(azureCdnPlatform);
_cloudStorageContainerName = ValidateAzureContainerName(JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.AzureCdnCloudStorageContainerName));
return true;
}
catch (Exception exception)
{
ApplicationInsights.TrackException(exception);
Trace.TraceError(exception.ToString());
}
return false;
}
示例11: Export
public async Task<string> Export()
{
var sourceConnBuilder = new SqlConnectionStringBuilder(_processorSettings.SourceConnectionString);
string exportBlobUri = null;
try
{
var ieHelper = new ImportExportHelper(_log)
{
EndPointUri = Helpers.GetEndpointUris()[_processorSettings.SourceAzureEndpointName.ParseEnum(Endpoint.None)],
StorageKey = _importExportSettings.StorageKey,
ServerName = sourceConnBuilder.DataSource.Replace("tcp:", string.Empty).Replace(",1433", string.Empty),
DatabaseName = sourceConnBuilder.InitialCatalog,
UserName = sourceConnBuilder.UserID,
Password = sourceConnBuilder.Password
};
exportBlobUri = string.Format("https://{0}.blob.core.windows.net/{1}/{2}-{3:yyyyMMddHHmmssff}.bacpac", _importExportSettings.StorageAccountName, _importExportSettings.StorageContainer, ieHelper.DatabaseName.ToLower(), DateTime.UtcNow);
var exportBlobPath = ieHelper.DoExport(exportBlobUri);
if (exportBlobPath == null)
{
_log.Error("Could not complete the export step for Backup and Restore of {SourceDatabase} to {ExportBlobPath}", _processorSettings.SourceConnectionString.ToSecretConnectionString(), exportBlobUri);
throw new NullReferenceException("ImportExportHelper.DoExport()");
}
return exportBlobPath;
}
catch (Exception ex)
{
_log.Error(ex, "Could not Backup {SourceDatabase} to {ExportBlobPath}", _processorSettings.SourceConnectionString.ToSecretConnectionString(), exportBlobUri ?? string.Empty);
throw;
}
}
示例12: Init
public override bool Init(IDictionary<string, string> jobArgsDictionary)
{
try
{
PackageDatabase =
new SqlConnectionStringBuilder(
JobConfigurationManager.GetArgument(jobArgsDictionary,
JobArgumentNames.PackageDatabase,
EnvironmentVariableKeys.SqlGallery));
var storageGalleryCstr = Environment.GetEnvironmentVariable(EnvironmentVariableKeys.StorageGallery);
if (string.IsNullOrEmpty(storageGalleryCstr))
{
throw new ArgumentException("Environment variable for storage gallery is not defined");
}
ContentAccount = CloudStorageAccount.Parse(storageGalleryCstr);
return true;
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
return false;
}
示例13: TestInitializer
public void TestInitializer()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = @".\SQLEXPRESS";
builder.IntegratedSecurity = true;
builder.InitialCatalog = "DBBlogs";
SqlConnection connection1 = new SqlConnection(builder.ConnectionString);
connection1.Open();
_currentTransaction1 = connection1.BeginTransaction();
SqlConnection connection2 = new SqlConnection(builder.ConnectionString);
connection2.Open();
_currentTransaction2 = connection2.BeginTransaction();
MetaDataStore metaDataStore = new MetaDataStore();
metaDataStore.BuildTableInfoFor<Blog>();
var identityMap1 = new IdentityMap();
var identityMap2 = new IdentityMap();
_blogMapper1 = new BlogMapper(connection1,
_currentTransaction1,
metaDataStore,
new EntityHydrater(metaDataStore, identityMap1),
identityMap1);
_blogMapper2 = new BlogMapper(connection2,
_currentTransaction2,
metaDataStore,
new EntityHydrater(metaDataStore, identityMap2),
identityMap2);
}
示例14: CreateDatabase
/// <summary>
/// Creates a database on the server.
/// </summary>
/// <param name="sqlProviderConnectionString">Connection string</param>
/// <returns>Error</returns>
private string CreateDatabase(string sqlProviderConnectionString)
{
try
{
//parse database name
var builder = new SqlConnectionStringBuilder(sqlProviderConnectionString);
var databaseName = builder.InitialCatalog;
//now create connection string to 'master' dabatase. It always exists.
builder.InitialCatalog = "master";
var masterCatalogConnectionString = builder.ToString();
string query = string.Format("CREATE DATABASE [{0}] COLLATE SQL_Latin1_General_CP1_CI_AS", databaseName);
using (var conn = new SqlConnection(masterCatalogConnectionString))
{
conn.Open();
using (var command = new SqlCommand(query, conn))
{
command.ExecuteNonQuery();
}
}
return string.Empty;
}
catch (Exception ex)
{
return string.Format("An error occured when creating database: {0}", ex.Message);
}
}
示例15: Authorization_Form
public Authorization_Form(SqlConnectionStringBuilder con, SelectServer_Form selectServer_Form)
{
InitializeComponent();
this.connectionString = con;
this.selectServer_Form = selectServer_Form;
Configuration();
}