Tuesday, August 31, 2010

Using MySql with WebMatrix

There's a small problem that affects any attempt to connect to a database through a connection string using WebMatrix : there's an error in the documentation that leads you to try to use Database.OpenConnectionString when you should be using the currently undocumented Database.Open (as shown below).
If you install the MySql.Data.MySqlClient dll to the GAC then you won't need the dbproviderfactories entry shown below. If you don't install it to the GAC, create a bin directory in your application and drop the dll in there.

See also: Useful information on WebMatrix from Rick Strahl


1. web.config:



<?xml version="1.0"?>


<configuration>
<connectionStrings>
<add name="myconnection" connectionString="server=localhost;user id=dimanuser; password=; database=diman; pooling=false; charset=utf8;" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
    <system.web>
        <compilation debug="false" targetFramework="4.0" />
    </system.web>
<system.data>
<DbProviderFactories>
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.2.2.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
</DbProviderFactories>
</system.data>
</configuration>


2. Code:


<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
@{   
    var db = Database.Open("myconnection");
    string sql = "select * from standard_text where rank <  @0 order by rank"; 
} 
    <ul> 
@foreach(var row in db.Query(sql,30)){ 
        <li> @row.rank - @row.title</li> 
} 
    </ul> 
    </body>
</html> 
  

No comments:

Post a Comment