The MYSQL database is connected through MySql.Data.dll, MySql.Web.dll in Visual Studio 2010,
The data is then inserted and queried.
The contents of the Program.cs file are as follows:
C # code
- Using System;
- Using System.Collections.Generic;
- Using System.Linq;
- Using System.Text;
- Using MySql.Data.MySqlClient;
- Using System.Data;
- Namespace Databaseprogram
- {
- Class Program
- {
- static String mysqlconnectionstring = "SERVER=LOCALHOST;DATABASE=CSHARP; Uid=root; Pwd=admin ";
- static void Main (string[] args)
- {
- InsertData ();
- Selectdata ();
- }
- //Inserting data into the database
- public static void InsertData ()
- {
- Mysqlconnection conn = new Mysqlconnection (mysqlconnectionstring);
- Mysqlcommand command;
- Conn. Open ();
- Try
- {
- Command = conn. CreateCommand ();
- Command.commandtext = "INSERT into Phonebook (Id,name,mobile) VALUES (@id, @name, @mobile)";
- Command. Parameters.addwithvalue ("@id", 2);
- Command. Parameters.addwithvalue ("@name", "Yangjianzhou");
- Command. Parameters.addwithvalue ("@mobile", "1234567890");
- Command. ExecuteNonQuery ();
- }
- catch (Exception)
- {
- }
- finally
- {
- if (Conn. state = = ConnectionState.Open)
- {
- Conn. Close ();
- }
- }
- }
- //Read data from the database
- public static void Selectdata ()
- {
- Mysqlconnection conn = new Mysqlconnection (mysqlconnectionstring);
- Conn. Open ();
- Mysqldatareader dataReader = null;
- Mysqlcommand command = null;
- Try
- {
- Command = conn. CreateCommand ();
- Command.commandtext = "SELECT * from Phonebook";
- DataReader =command. ExecuteReader ();
- Console.WriteLine ();
- While (Datareader.read ())
- {
- Console.WriteLine ("id={0}, Name={1}, Mobile={2}", Datareader.getint16 (0), datareader.getstring (1), Datareader.getstring (2));
- Console.WriteLine ();
- }
- }
- catch (Exception)
- {
- }
- finally
- {
- if (!datareader.isclosed)
- {
- Datareader.close ();
- }
- if (Conn. state = = ConnectionState.Open)
- {
- Conn. Close ();
- }
- }
- }
- }
- }
The results of the operation are as follows:
The contents of the database are:
The query results are: