Acceso a MySQL desde C#
Este es un ejemplo simple de acceso a una BBDD Mysql con el driver 3, el 5 es beta y no está documentada la forma de conectar (o al menos no la encuentro).
Esta sería la clase:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Odbc;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (comprobar(login.Text, password.Text))
{
lblResultado.Text = "OK. Login correcto";
}
else
{
lblResultado.Text = "Error!. Login incorrecto";
}
}
private bool comprobar(string strLogin, string strPassword)
{
string cadenaConexion;
OdbcConnection conexion;
OdbcCommand sentencia;
OdbcDataReader resultado;
bool existe = false;
string consulta = "select * from usuarios where login= + strLogin + and password = sha1( + strPassword + )";
cadenaConexion ="DRIVER={MySQL ODBC 3.51 Driver};SERVER=localhost; DATABASE=telefonos;USER=root;PASSWORD=root;OPTION=3;";
lblQuery.Text = consulta;
// Creamos la instancia del objeto pasándole el string de conexion
conexion = new OdbcConnection(cadenaConexion);
// Abrimos la conexion
conexion.Open();
// Creamos la instancia del objeto para ejecutar comandos
sentencia = new OdbcCommand(consulta, conexion);
// Y la ejecutamos
resultado = sentencia.ExecuteReader();
existe = resultado.HasRows;
// Cerramos la conexion con la BD
conexion.Close();
return existe;
}
}
Y por su parte, la página ASP.NET asociada:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Página sin título</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label2" runat="server" Text="Login"></asp:Label>
<asp:TextBox ID="login" runat="server"></asp:TextBox> <br />
<asp:Label ID="Label1" runat="server" Text="Password"></asp:Label>
<asp:TextBox ID="password" runat="server" OnTextChanged="TextBox1_TextChanged" TextMode="Password"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Comprobar" /><br />
<asp:Label ID="lblResultado" runat="server"></asp:Label>
<br />
<asp:Label ID="lblQuery" runat="server"></asp:Label></div>
</form>
</body>
</html>
pello.io