Database::OpenConnectionString Method (String, String)
Opens a connection to a database using a connection string and the specified provider.
Assembly: WebMatrix.Data (in WebMatrix.Data.dll)
public: static Database^ OpenConnectionString( String^ connectionString, String^ providerName )
Parameters
- connectionString
- Type: System::String
The connection string that contains information that is used to connect to a database.
- providerName
- Type: System::String
(Optional) The name of the .NET Framework data provider to use to connect to the data source.
| Exception | Condition |
|---|---|
| ArgumentException | connectionString is nullptr or empty. |
The OpenConnectionString method differs from the Open method, which uses the name of a connection string that is stored in the Web.config file.
You might use the OpenConnectionString method when a connection string is programmatically generated or is provided by the user.
The following example shows how to use the OpenConnectionString method to connect to a database.
@{
var connectionString = "Data Source=.\\SQLExpress;Initial Catalog=SmallBakery;Integrated Security=True";
var providerName = "System.Data.SqlClient";
var db = Database.OpenConnectionString(connectionString, providerName);
var selectQueryString = "SELECT * FROM Product ORDER BY Name";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Small Bakery Products</title>
<style>
table, th, td {
border: solid 1px #bbbbbb;
border-collapse: collapse;
padding: 2px;
}
</style>
</head>
<body>
<h1>Small Bakery Products</h1>
<div>
<table>
<thead>
<tr>
<th>Id</th>
<th>Product</th>
<th>Desciprion</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@foreach(var row in db.Query(selectQueryString)) {
<tr>
<td >@row.Id</td>
<td>@row.Name</td>
<td>@row.Description</td>
<td>@row.Price</td>
</tr>
}
</tbody>
</table>
<a href=@Href("~/InsertProducts")>Add Products</a>
</div>
</body>
</html>
Show: