Web.config. It is ideal to put your connection string in Web.config in your ASP.NET project. You will have to find the appropriate blocks in the XML config file.
And In this next XML element example, I use the connection string name of WhateverName.
<!-- This XML should be put in Web.config -->
<add name="WhateverName" connectionString="Exact string shown above"/>
Using. At the top are your using-statements. Add these two using-statements at the top. The first adds the database stuff, and the second allows you to access your connection string.
Using statements, C#:
New. We can create an OdbcConnection by combining it with the using-statement. The next code block gets our special connection string from the Web.config file.
Info The OdbcConnection with the identifier "c" is a new connection to the database. These are automatically pooled and shared.
// Try to connect to the database based on our stored connection string.
string conString = WebConfigurationManager.ConnectionStrings["WhateverName"].ConnectionString;
using (OdbcConnection c = new OdbcConnection(conString))
// We are now connected.// Now we can use OdbcCommand objects to accomplish things.
MySQL. Here we declare a new OdbcCommand object, add a parameter to the command object, and then read in data from the database. Note the question mark in the command text.
Info The OdbcCommand takes the connection object as the second parameter. The paramWord string is added to the command.
And The parameter is named "var" but that is not important. The parameter is added in the first question mark.
Result It looks through the table and find the rows where the MagicKey column is equal to paramWord.
using (OdbcCommand c = new OdbcCommand("SELECT ColumnWord FROM OkieTable WHERE MagicKey = ?", con))
using (OdbcDataReader reader = c.ExecuteReader())
string word = reader.GetString(0);
// Word is from the database. Do something with it.
A summary. Here we fixed bugs with OdbcConnection. This can be applied to any ADO.NET provider, from SqlConnection objects to SqlCeConnections and SQLiteConnections.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 8, 2022 (edit link).