Difference between revisions of "C#:Read From a Database"

From Progzoo
Jump to: navigation, search
(Read from a MySQL database)
(Read from a MySQL database)
Line 57: Line 57:
 
</question>
 
</question>
  
=Read from a MySQL database=
+
[Access a MySQL Database Table from C#]
<question xmlns:htm="http://www.w3.org/1999/xhtml" lang="cs" className='Demo'>
 
To read from a '''non''' SQL Server database you can use the classes in System.Data.OdbcClient
 
*OdbcCommand
 
*OdbcConnection
 
*OdbcDataReader
 
The Odbc connection must be created first; this one is called MySQLscott.
 
*Download the mysql-odbc-connector from mysql.com
 
*Create the ODBC connection from Start/Control Panel/Administrative Tools/Datasources (ODBC)/System DSN
 
<p class="imper">Read the name and population for each country
 
with a population of more than 200000000.
 
</p>
 
<prog lang="cs">
 
using System;
 
using System.Data.Odbc;
 
class Demo{
 
  public static void Main(string[] args){
 
    try{
 
      OdbcCommand comm = new OdbcCommand();
 
      comm.Connection = new OdbcConnection(
 
        "DSN=MySQLscott;user=scott;password=tiger;");
 
      String sql = @"SELECT name, population
 
                      FROM bbc
 
                    WHERE population>200000000";
 
      comm.CommandText = sql;
 
      comm.Connection.Open();
 
      OdbcDataReader cursor = comm.ExecuteReader();
 
      while (cursor.Read())
 
        Console.WriteLine(cursor["name"] + "\t"+
 
                          cursor["population"]);
 
      comm.Connection.Close();
 
    }catch (Exception e){
 
      Console.WriteLine(e.ToString());
 
    }
 
  }
 
}
 
</prog>
 
</question>
 

Revision as of 08:00, 19 June 2008

The .Net framework includes several "parallel" namespaces that connect you to a database. System.Data.SqlClient connects to Microsoft's own database SQL Server; alternatives include System.Data.Odbc and System.Data.OleDb and System.Data.OracleClient

Read from a SQL Server database

To read from a SQL Server database you can use the classes in System.Data.SqlClient

  • SqlCommand
  • SqlConnection
  • SqlDataReader
Connection parameters
valuedescription
127.0.0.1 the IP address database server;
gisq the name of the database;
scott user name;
tiger the password;

Read the name and population for each country with a population of more than 200000000.

The SQL statement is:
SELECT name, population
FROM bbc
WHERE population>200000000

The table bbc has columns:

  • name
  • region
  • area
  • population
  • gdp


[Font] [Default] [Show] [Resize] [History] [Profile]

[Access a MySQL Database Table from C#]