Connecting to MySQL Database with ASP.NET Web Pages (Razor)

johna by | May 20, 2011 | ASP.NET Web Pages Web Development

To connect to a MySQL database from ASP.NET Web Pages (Razor) you need to do the following:

1. Add a "Bin" ASP.NET folder to your project and copy the file MySQl.Data.dll in to it.

You can obtain this file by downloading the latest version of the MySQL Connector/NET (http://dev.mysql.com/downloads/connector/net/), installing it, then locate the file in the installation folder.

2. In your web.config file add a connection string for your database, for example:

<configuration>
<connectionStrings>
<add name="Any-name" connectionString="Server=server-name-or-ip;Port=3306;Database=database-name;Uid=username;Pwd=password;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>

3. In your code you can then open a connection to your database:

var db = Database.Open("Any-name");


Update

If you get the error message "Unable to find the requested .Net Framework Data Provider. It may not be installed." then you will also need to add some extra lines to web.config.

<configuration>
<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" />
</DbProviderFactories>
</system.data>
</configuration>

Related Posts

Web Development

How to set up a debugging using the Turnkey Linux LAMP stack and VS Code

by johna | December 19, 2023
The second part in my guide to setting up a website and database using the Turnkey Linux LAMP stack.

Website Hosting Web Development

How to set up a website and database using the Turnkey Linux LAMP stack

by johna | November 18, 2023
If you need to host your own website for the purposes of web development, Turnkey Linux LAMP Stack is an easy to install all-in-one solution that you can set up on a spare computer or a VM (Virtual Machine).

ASP.NET Web Pages

ASP.NET Web Pages cshtml files not recompiling on server

by johna | August 18, 2020
I have an old website written in ASP.NET v4.x Web Pages v1.0.0.0 and when I upload changes to my shared hosting provider some cshtml files update fine and I can see the changes, but some do not.

Comments

Tony Dunsworth

by Tony Dunsworth | August 2, 2013

Would this work with the same set up for an Oracle database using ODP.NET dll's?

Reply

John Avis

by John Avis | August 2, 2013

You can connect to an Oracle database (or any ADO.NET provider) in the same way with WebPages. Just add your connection string.

Reply

Leave a Comment

About

...random postings about web development and programming, Internet, computers and electronics topics.

I recommend ASPnix for web hosting and Crazy Domains for domain registration.

Subscribe

Get the latest posts delivered to your inbox.