Mysql queries uitvoeren Opus
Jump to navigation
Jump to search
Als je zonder ODBC koppelingen wilt werken kan je direct met MYSQL verbinden door de MYSQL .NET 5.1 conntector [hier te downloaden]. Vervolgens kan je hem installeren.
Wanneer je aan een nieuw project begint moet je de mysql module als reference toevoegen:
File:Capture.jpg
using System; using System.Collections.Generic; using System.Text; using MySql; using MySql.Data; using MySql.Data.MySqlClient; namespace ConsoleApp { class Program { static void Main(string[] args) { //Set up connection string string connString = @" server = localhost; database = dbname; user id = root; password = pass; "; //Set up query string string sql = @" select * from table"; MySqlConnection conn = null; MySqlDataReader reader = null; try { //open connection conn = new MySqlConnection(connString); conn.Open(); //Execute the Query MySqlCommand cmd = new MySqlCommand(sql, conn); reader = cmd.ExecuteReader(); //Display output header Console.WriteLine("This programma demonstrates the use of" + "the MYSQL Server Data Provider"); Console.WriteLine("Quering the database {0} with {1}\n" , conn.Database , cmd.CommandText ); Console.WriteLine("{0} | {1}" ,"functienaam".PadLeft(10) ,"vakgebied".PadLeft(10) ); //Process the result set while (reader.Read()) { Console.WriteLine("{0} | {1}" , reader["functienaam"].ToString().PadLeft(10) , reader["vakgebied"].ToString().PadLeft(10) ); } } catch (Exception e) { Console.WriteLine("Error " + e); } finally { //reader.Close(); conn.Close(); Console.Read(); } } } }