简体   繁体   中英

Connection String for MySQL (C# in asp.net)

I am using a the C# ODBC object in asp.net to connect up to a MySQL server hosted on another computer (on the same network).

<%@ Import Namespace="System.Data.Odbc" %>
<html>
<body>
<script language="C#" runat="server">

protected void Page_Load(Object Src, EventArgs E) 
{
try
{
using(OdbcConnection connection = new OdbcConnection("DRIVER={MySQL ODBC 5.51.30 Driver};Database=test;Server=192.168.1.109;UID=Username;PWD=Password;"))
{
    connection.Open();
    using(OdbcCommand command = new OdbcCommand("SELECT * FROM tablename", connection))
    using(OdbcDataReader dr = command.ExecuteReader())
    {
        while(dr.Read())
            Response.Write(dr["name"].ToString() + "<br>");
        dr.Close();
    }
    connection.Close();
}
}
catch(Exception ex)
{
Response.Write("An error occurred: " + ex.Message);
}
}
</script>
</body>
</html>

I am currently getting this error when I run the code:

An error occurred: ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

I am hosting this on a Microsoft IIS server, with ASP.net enabled. Would I be able to get any help with fixing this error?

Link to image of my MySQL server: http://i.stack.imgur.com/4NYCr.png

Would I be able to get any help with fixing this error?

Yes, you would. So, your only question was answered. And now? Please think a little more about WHAT you ask.

TO your problem.

Like always, http://www.connectionstrings.com/ is the primary resource for this ;) Anything you ever wanted to know about connectionstrings on one place.

For MySQL (asuming 5.2) you can find (for ODBC) the solution at:

http://www.connectionstrings.com/mysql-connector-odbc-5-2/

Now, your string looks good - so I start assuming you have a driver problem. I would assume that wherever you run it it just does not have - the ODBC ddriver installed.

THAT SAID: there is no real reason to use ODBC (which has native prerequisites) and not a (managed) MySQL Driver?

if you really miss the ODBC driver, you can ind the downloads at http://www.mysql.com/products/connector/ . But I would really not use ODBC here - not with a native connector available.

I think you better use MySQlConnection as well as MyqlCommand for your needs: eg:

 server = "localhost";
        database = "connectcsharptomysql";
        uid = "username";
        password = "password";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" + 
        database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

        connection = new MySqlConnection(connectionString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM